use std::io::Write;
use std::io;
use std::collections::HashMap;
use std::sync::Arc;
use crate::error::{Result, PipitError};
use crate::lazy_memory_pool::LazyMemoryPool;
use crate::advanced_optimizations;
use crate::advanced_optimizations::ValueKind;
use crate::concurrent_gc::ConcurrentGC;
use crate::memory_optimizer::MemoryOptimizer;
use crate::zero_copy_memory::ZeroCopyMemory;
use crate::memory_compression::MemoryCompressor;
use crate::predictive_memory_allocator::PredictiveMemoryAllocator;
use crate::smart_memory_manager::{SmartMemoryManager, SmartMemoryConfig};
use crate::large_object_optimization::{LargeObjectPool, LargeObjectStrategy, ObjectSize};
use crate::riscv_vm::{RV32IVirtualMachine, RV32IInstruction};
use crate::shared_data::SharedData;
use crate::types::{Type, TypeChecker, TypeEnvironment};

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Module {
    Core,
    IO,
    Math,
    String,
    OS,
    Concurrent,
    Syscall,
}

#[derive(Debug, Clone)]
pub struct ModuleRegistry {
    pub loaded_modules: HashMap<Module, bool>,
    pub exports: HashMap<String, String>, // 别名到原始名称的映射
    pub exported_values: HashMap<String, Value>, // 别名到值的映射
    pub imports: HashMap<String, String>, // 本地别名到远程名称的映射
}

impl ModuleRegistry {
    pub fn new() -> Self {
        ModuleRegistry {
            loaded_modules: HashMap::new(),
            exports: HashMap::new(),
            exported_values: HashMap::new(),
            imports: HashMap::new(),
        }
    }

    pub fn register_module(&mut self, module: Module, loaded: bool) {
        self.loaded_modules.insert(module, loaded);
    }

    pub fn is_module_loaded(&self, module: &Module) -> bool {
        *self.loaded_modules.get(module).unwrap_or(&false)
    }

    pub fn load_module(&mut self, module: Module) -> Result<()> {
        self.loaded_modules.insert(module, true);
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
        io::stdout().flush()?;
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
        io::stdout().flush()?;
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }

    pub fn unload_module(&mut self, module: Module) -> Result<()> {
        self.loaded_modules.insert(module, false);
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    // 添加导出符号
    pub fn add_export(&mut self, alias: String, original_name: String) {
        self.exports.insert(alias, original_name);
    }
    
    // 存储导出的值
    pub fn store_exported_value(&mut self, alias: String, value: Value) {
        self.exported_values.insert(alias, value);
    }
    
    // 添加导入
    pub fn add_import(&mut self, local_alias: String, remote_name: String) {
        self.imports.insert(local_alias, remote_name);
    }
    
    // 获取导出的值
    pub fn get_exported_value(&self, name: &str) -> Option<&Value> {
        self.exported_values.get(name)
    }
}

// 绑定标准库syscall模块的函数 - 暂时注释掉以避免编译错误
// extern "C" {
//     fn pipit_syscall_read_int() -> i32;
//     fn pipit_syscall_read_float() -> f64;
//     fn pipit_syscall_read_string() -> *mut c_char;
//     fn pipit_syscall_read_line() -> *mut c_char;
//     fn pipit_syscall_print_int(value: i32);
//     fn pipit_syscall_print_float(value: f64);
//     fn pipit_syscall_print_string(value: *const c_char);
//     fn pipit_syscall_print_line(value: *const c_char);
//     fn pipit_syscall_getenv(name: *const c_char) -> *mut c_char;
//     fn pipit_syscall_system(command: *const c_char) -> i32;

// #[cfg(feature = "stdlib")]
// mod stdlib_bindings {
//     use super::*;
//     
//     // 原生函数实现
//     pub fn native_read_int(vm: &mut VirtualMachine) {
//         let value = unsafe { pipit_syscall_read_int() };
//         vm.stack.push(Value::Integer(value));
//     }

//     pub fn native_read_float(vm: &mut VirtualMachine) {
//         let value = unsafe { pipit_syscall_read_float() };
//         vm.stack.push(Value::Float(value));
//     }
//     pub fn native_read_string(vm: &mut VirtualMachine) {
//         let c_string = unsafe { pipit_syscall_read_string() };
//         if !c_string.is_null() {
//             let c_str = unsafe { CStr::from_ptr(c_string) };
//             if let Ok(rust_str) = c_str.to_str() {
//                 vm.stack.push(Value::String(rust_str.to_string()));
//             }
//         }
//     }
//     
//     pub fn native_print_int(vm: &mut VirtualMachine) {
//         if let Some(Value::Integer(value)) = vm.stack.pop() {
//             unsafe { pipit_syscall_print_int(value) };
//         }
//     }
//     
//     pub fn native_print_float(vm: &mut VirtualMachine) {
//         if let Some(Value::Float(value)) = vm.stack.pop() {
//             unsafe { pipit_syscall_print_float(value) };
//         }
//     }
//     
//     pub fn native_print_string(vm: &mut VirtualMachine) {
//         if let Some(Value::String(value)) = vm.stack.pop() {
//             if let Ok(c_string) = CString::new(value) {
//                 unsafe { pipit_syscall_print_string(c_string.as_ptr()) };
//             }
//         }
//     }
//     
//     pub fn native_getenv(vm: &mut VirtualMachine) {
//         if let Some(Value::String(name)) = vm.stack.pop() {
//             if let Ok(c_string) = CString::new(name) {
//                 let result = unsafe { pipit_syscall_getenv(c_string.as_ptr()) };
//                 if !result.is_null() {
//                     let c_str = unsafe { CStr::from_ptr(result) };
//                     if let Ok(rust_str) = c_str.to_str() {
//                         vm.stack.push(Value::String(rust_str.to_string()));
//                     }
//                     return;
//                 }
//             }
//             vm.stack.push(Value::String("".to_string()));
//         }
//     }
// }

// #[cfg(feature = "stdlib")]
// pub fn register_stdlib(vm: &mut VirtualMachine) {
//     use stdlib_bindings::*;
//     vm.register_native_function("read_int".to_string(), native_read_int);
//     vm.register_native_function("read_float".to_string(), native_read_float);
//     vm.register_native_function("read_string".to_string(), native_read_string);
//     vm.register_native_function("print_int".to_string(), native_print_int);
//     vm.register_native_function("print_float".to_string(), native_print_float);
//     vm.register_native_function("print_string".to_string(), native_print_string);
//     vm.register_native_function("getenv".to_string(), native_getenv);
// }

// 添加类定义结构体
#[derive(Debug, Clone, PartialEq)]
pub struct ClassDefinition {
    pub name: String,
    pub methods: HashMap<String, (usize, usize)>, // 方法名到(地址, 参数数量)的映射
    pub class_id: usize, // 类唯一标识符，用于内联缓存
}

impl ClassDefinition {
    pub fn new(name: String, class_id: usize) -> Self {
        ClassDefinition {
            name,
            methods: HashMap::new(),
            class_id,
        }
    }
}

// 类实例结构体
#[derive(Debug, Clone, PartialEq)]
pub struct ClassInstance {
    pub class_def: ClassDefinition,
    pub fields: HashMap<String, Value>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Integer(i32),
    Float(f64),
    Boolean(bool),
    String(String),
    Array(Vec<Value>),
    Struct(HashMap<String, Value>), // 新增结构体支持
    Function(usize), // 函数值支持
    Instance(Box<ClassInstance>), // 类实例
    Class(ClassDefinition), // 类定义
    NativeFunction(String), // 原生函数支持
    CachedValue(Box<Value>), // 缓存值
    Shared(SharedData), // 共享数据
    Null, // 空值类型
    
    // 添加共享数据类型，用于虚拟机间0拷贝通信
    // Shared(SharedData),
}

impl Value {
    // 获取整数值的辅助方法
    pub fn as_integer(&self) -> Option<i32> {
        match self {
            Value::Integer(i) => Some(*i),
            _ => None,
        }
    }
    
    // 将Value转换为ValueKind
    pub fn as_value_kind(&self) -> advanced_optimizations::ValueKind {
        match self {
            Value::Integer(_) => advanced_optimizations::ValueKind::Integer,
            Value::Float(_) => advanced_optimizations::ValueKind::Float,
            Value::Boolean(_) => advanced_optimizations::ValueKind::Boolean,
            Value::String(_) => advanced_optimizations::ValueKind::String,
            Value::Array(_) => advanced_optimizations::ValueKind::Array,
            Value::Struct(_) => advanced_optimizations::ValueKind::Struct,
            Value::Function(_) => advanced_optimizations::ValueKind::Function,
            Value::Instance(_) => advanced_optimizations::ValueKind::Instance,
            Value::Class(_) => advanced_optimizations::ValueKind::Class,
            Value::NativeFunction(_) => advanced_optimizations::ValueKind::NativeFunction,
            Value::CachedValue(_) => advanced_optimizations::ValueKind::CachedValue,
            Value::Shared(_) => advanced_optimizations::ValueKind::Shared,
            Value::Null => advanced_optimizations::ValueKind::Other,
        }
    }
    
    // 获取值的类ID（用于内联缓存）
    pub fn get_class_id(&self) -> Option<usize> {
        match self {
            Value::Instance(instance) => Some(instance.class_def.class_id),
            Value::Class(class_def) => Some(class_def.class_id),
            _ => None,
        }
    }

    // 获取值的类名
    pub fn get_class_name(&self) -> Option<&String> {
        match self {
            Value::Instance(instance) => Some(&instance.class_def.name),
            Value::Class(class_def) => Some(&class_def.name),
            _ => None,
        }
    }
}

// 句柄收集器
#[derive(Debug)]
pub struct HandleCollector {
    pub handles: Vec<Value>, // 对象索引列表
    pub capacity: usize,     // 收集器容量
}

impl HandleCollector {
    pub fn new(capacity: usize) -> Self {
        HandleCollector {
            handles: Vec::with_capacity(capacity),
            capacity,
        }
    }
    
    pub fn add_handle(&mut self, handle: usize) -> Result<()> {
        if self.handles.len() < self.capacity {
            self.handles.push(Value::Function(handle));
            Ok(())
        } else {
            Err(PipitError::RuntimeError("Handle collector is full".to_string()))
        }
    }

    pub fn get_handles(&self) -> &Vec<Value> {
        &self.handles
    }
    
    pub fn clear(&mut self) {
        self.handles.clear();
    }
}

// 栈帧收集器
#[derive(Debug)]
pub struct StackFrameCollector {
    pub frames: Vec<CallFrame>, // 栈帧列表
    pub capacity: usize,        // 收集器容量
}

impl StackFrameCollector {
    pub fn new(capacity: usize) -> Self {
        StackFrameCollector {
            frames: Vec::with_capacity(capacity),
            capacity,
        }
    }
    
    pub fn add_frame(&mut self, frame: CallFrame) -> Result<()> {
        if self.frames.len() < self.capacity {
            self.frames.push(frame);
            Ok(())
        } else {
            Err(PipitError::RuntimeError("Stack frame collector is full".to_string()))
        }
    }
    
    pub fn get_frames(&self) -> &Vec<CallFrame> {
        &self.frames
    }
    
    pub fn clear(&mut self) {
        self.frames.clear();
    }
}

// 缓存池（用于存储惰性数据）
#[derive(Debug)]
pub struct CachePool {
    pub cached_values: HashMap<String, Value>, // 缓存的值，使用字符串键
    pub max_size: usize,           // 最大大小
}

impl CachePool {
    pub fn new(max_size: usize) -> Self {
        CachePool {
            cached_values: HashMap::with_capacity(max_size),
            max_size,
        }
    }
    
    pub fn cache_value(&mut self, value: Value) -> Result<()> {
        // 这个方法保留用于向后兼容
        if self.cached_values.len() < self.max_size {
            let key = format!("auto_{}", self.cached_values.len());
            self.cached_values.insert(key, Value::CachedValue(Box::new(value)));
            Ok(())
        } else {
            Err(PipitError::RuntimeError("Cache pool is full".to_string()))
        }
    }
    
    pub fn get_cached_value(&self, index: usize) -> Option<&Value> {
        // 这个方法保留用于向后兼容
        let key = format!("auto_{}", index);
        self.cached_values.get(&key)
    }
    
    pub fn clear(&mut self) {
        self.cached_values.clear();
    }
    
    // 新增的get方法
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.cached_values.get(key)
    }
    
    // 新增的put方法
    pub fn put(&mut self, key: String, value: Value) {
        // 如果缓存已满，移除一个元素
        if self.cached_values.len() >= self.max_size {
            if let Some(first_key) = self.cached_values.keys().next().cloned() {
                self.cached_values.remove(&first_key);
            }
        }
        self.cached_values.insert(key, value);
    }
}

// 指令枚举定义
    #[derive(Debug, Clone)]
    #[derive(PartialEq)]
    pub enum Instruction {
        // --- 栈指令 ---
        Push(Value),
        Add,
        Sub,
        Mul,
        Div,
        Mod,                // 取模运算
        Pow,                // 求幂运算
        Equal,              // 相等比较
        LessThan,           // 小于比较
        GreaterThan,        // 大于比较
        And,                // 逻辑与
        Or,                 // 逻辑或
        Not,                // 逻辑非
        Jump(usize),        // 无条件跳转
        JumpIfFalse(usize), // 条件跳转（假时跳转）
        JumpIfTrue(usize),  // 条件跳转（真时跳转）
        Call(usize),
        Return,
        Halt,
        Nop,                // 空操作（用于优化过程中的占位）
        RegisterToStack(u8), // 将寄存器中的值压入栈中
        StackToRegister(usize, u8), // 将栈中指定索引的值存入指定的寄存器中
        Print,                    // 打印栈顶值（不换行）
        Println,                  // 打印栈顶值（换行）
        PrintStr(String),         // 打印字符串
        StoreVar(i32),          // 存储变量到指定位置
        LoadVar(i32),           // 从指定位置加载变量
        MakeArray(usize),         // 创建包含n个元素的数组
        ArrayGet,                 // 获取数组元素 arr[index]
        ArraySet,                 // 设置数组元素 arr[index] = value
        ArrayLength,              // 获取数组长度
        MakeStruct(usize),          // 创建结构体
        StructGet(String),        // 获取结构体字段
        StructSet(String),        // 设置结构体字段
        MakeClass(usize, usize),    // 创建类实例 (class_id, arg_count)
        CallMethod(String, usize),  // 调用方法 (method_name, arg_count)
        SysCall(String),          // 系统调用
        NativeCall(String),       // 原生函数调用
        
        // 错误处理相关指令
        TryBegin(usize),          // try块开始，参数是catch块的位置
        TryEnd,                   // try块结束
        CatchBegin(usize),        // catch块开始，参数是finally块的位置
        CatchEnd,                 // catch块结束
        FinallyBegin(usize),      // finally块开始，参数是finally之后的位置
        FinallyEnd,               // finally块结束
        Throw,                    // 抛出异常
        CreateError(String),      // 创建错误对象
        
        // 模块系统相关指令
        LoadModule(String),       // 加载模块
        ImportSymbol(String, String), // 导入符号 (模块名, 符号名)
        ExportSymbol(String, String), // 导出符号 (符号名, 别名)

        // --- 寄存器指令 ---
        RegLoadConst(u8, Value),      // reg[u8] = value
    RegMove(u8, u8),              // reg[dst] = reg[src]
    RegAdd(u8, u8, u8),           // reg[dst] = reg[src1] + reg[src2]
    RegSub(u8, u8, u8),           // reg[dst] = reg[src1] - reg[src2]
    RegMul(u8, u8, u8),           // reg[dst] = reg[src1] * reg[src2]
    RegDiv(u8, u8, u8),           // reg[dst] = reg[src1] / reg[src2]
    RegMod(u8, u8, u8),           // reg[dst] = reg[src1] % reg[src2]
    RegPow(u8, u8, u8),           // reg[dst] = reg[src1] ^ reg[src2]
    RegJump(usize),               // pc = target
    RegJumpIfFalse(u8, usize),    // if !reg[u8] then pc = target
    RegJumpIfTrue(u8, usize),     // if reg[u8] then pc = target
    RegCall(usize, u8, u8),       // 调用函数 (地址, 返回寄存器, 参数数量)
    RegReturn(u8),                // 从函数返回, reg[u8]为返回值
    RegPrint(u8),                 // 打印寄存器中的值

    // 循环优化专用指令
    LoopInit(u8, Value),          // 初始化循环计数器 reg[u8] = value
    LoopInc(u8),                  // 循环自增 reg[u8]++
    LoopDec(u8),                  // 循环自减 reg[u8]--
    LoopCheck(u8, Value, usize),  // 检查循环条件 reg[u8] <? value then jump
    LoopEnd,                      // 循环结束标记
    
    // 计时器相关指令
    TimerStart,                   // 启动计时器
    TimerStop,                    // 停止计时器
    TimerRead(u8),                // 读取计时器值到寄存器 reg[u8] = timer
    
    // 指针操作指令
    PtrLoad(u8, u8),              // 从指针位置加载值 reg[u8] = *reg[u8_src]
    PtrStore(u8, u8),             // 存储值到指针位置 *reg[u8_dst] = reg[u8_src]
    PtrAdd(u8, Value),            // 指针加法 reg[u8] += value
    PtrSub(u8, Value),            // 指针减法 reg[u8] -= value
    
    // 专用指针操作指令
    LoopPtrLoad(u8, u8),          // 从循环指针加载值 reg[u8] = *loop_ptr[u8_src]
    LoopPtrStore(u8, u8),         // 存储值到循环指针 *loop_ptr[u8_dst] = reg[u8_src]
    TimerPtrLoad(u8),             // 从计时器指针加载值 reg[u8] = *timer_ptr
    TimerPtrStore(u8),            // 存储值到计时器指针 *timer_ptr = reg[u8]
    GeneralPtrLoad(u8, u8),       // 从通用指针加载值 reg[u8] = *general_ptr[u8_src]
    GeneralPtrStore(u8, u8),      // 存储值到通用指针 *general_ptr[u8_dst] = reg[u8_src]
    
    // 缓存相关指令
    CachePush(Value),             // 将值推入缓存
    CachePop(u8),                 // 从缓存弹出值到寄存器
    CacheStore(usize),            // 将栈顶值存储到缓存池指定位置
    CacheLoad(usize, u8),         // 从缓存池加载值到寄存器
    CollectorCombine,             // 组合收集器
    CollectorClear,               // 清空收集器

    // 内联缓存相关指令
    ICCreate(usize),               // 创建内联缓存
    ICLookup(usize, usize, u8),    // 内联缓存查找
    ICGetMethod(usize, usize, u8), // 获取方法内联缓存
    ICUpdate(usize, usize, usize, usize), // 更新内联缓存
    ICUpdateMethod(usize, usize, usize, usize),  // 更新方法内联缓存
}

// 扩展的栈帧结构，支持可扩展大小
#[derive(Debug)]
pub struct ExtendedCallFrame {
    pub return_address: usize,
    pub local_variables: HashMap<i32, Value>,
    pub arg_count: usize,
    pub function_address: usize,
    pub registers: Vec<Value>,
    pub max_stack_size: usize, // 最大栈大小
    pub current_stack_size: usize, // 当前栈大小
}

impl ExtendedCallFrame {
    pub fn new(return_address: usize, function_address: usize, arg_count: usize, reg_count: usize, max_stack_size: usize) -> Self {
        ExtendedCallFrame {
            return_address,
            local_variables: HashMap::with_capacity(arg_count + 4),
            arg_count,
            function_address,
            registers: vec![Value::Integer(0); reg_count],
            max_stack_size,
            current_stack_size: 0,
        }
    }
    
    // 扩展栈帧大小
    pub fn extend_stack(&mut self, additional_size: usize) -> Result<()> {
        let new_size = self.current_stack_size + additional_size;
        if new_size <= self.max_stack_size {
            self.current_stack_size = new_size;
            Ok(())
        } else {
            Err(PipitError::RuntimeError("Stack frame size limit exceeded".to_string()))
        }
    }
}

impl CallFrame {
    pub fn new(return_address: usize, function_address: usize, arg_count: usize, reg_count: usize, max_locals: usize) -> Self {
        // 预分配栈帧空间，支持负索引和正索引访问
        // 例如：分配256个槽位，基址为128，支持索引范围[-128, 127]
        let frame_size = max_locals.max(256);
        let stack_base = (frame_size / 2) as i32;
        
        CallFrame {
            return_address,
            stack_frame: vec![Value::Integer(0); frame_size],
            stack_base,
            arg_count,
            function_address,
            registers: vec![Value::Integer(0); reg_count],
        }
    }
    
    // 获取局部变量（支持负索引）
    pub fn get_local(&self, index: i32) -> Option<&Value> {
        let actual_index = self.stack_base + index;
        if actual_index >= 0 && (actual_index as usize) < self.stack_frame.len() {
            Some(&self.stack_frame[actual_index as usize])
        } else {
            // 返回0值而不是None，提高容错性
            static DEFAULT_VALUE: Value = Value::Integer(0);
            Some(&DEFAULT_VALUE)
        }
    }
    
    // 设置局部变量（支持负索引和动态栈增长）
    pub fn set_local(&mut self, index: i32, value: Value) {
        let mut actual_index = self.stack_base + index;
        
        // 动态栈增长逻辑
        if actual_index >= self.stack_frame.len() as i32 {
            // 需要向后扩展栈
            let new_size = (actual_index + 1).max(self.stack_frame.len() as i32 * 2);
            self.stack_frame.resize(new_size as usize, Value::Integer(0));
        } else if actual_index < 0 {
            // 需要向前扩展栈并调整基址
            let expansion_size = (-actual_index) as usize;
            let new_size = self.stack_frame.len() + expansion_size;
            
            // 创建新的栈帧，先填充0，然后复制旧内容
            let mut new_stack_frame = vec![Value::Integer(0); new_size];
            // 使用clone_from_slice替代copy_from_slice，因为Value不实现Copy trait
            new_stack_frame[expansion_size..].clone_from_slice(&self.stack_frame);
            
            // 更新栈帧和基址
            self.stack_frame = new_stack_frame;
            self.stack_base += expansion_size as i32;
            actual_index = 0; // 现在第一个元素的索引变为0
        }
        
        // 安全地设置值
        if actual_index >= 0 && (actual_index as usize) < self.stack_frame.len() {
            self.stack_frame[actual_index as usize] = value;
        }
    }
    
    // 获取参数数量
    pub fn get_param_count(&self) -> usize {
        self.arg_count
    }
}

// 对象状态枚举
#[derive(Debug, Clone, PartialEq)]
pub enum ObjectState {
    Active,      // 活跃状态
    Inactive,    // 非活跃状态，等待销毁
    Destroyed,   // 已销毁
    Tombstone,   // 墓碑状态（已销毁但保留一段时间）
}

// 从advanced_optimizations导入类型
type EscapeInfo = advanced_optimizations::EscapeInfo;
type CallSiteStats = advanced_optimizations::CallSiteStats;

// 对象存储信息
#[derive(Debug, Clone)]
pub struct ObjectInfo {
    pub value: Value,
    pub state: ObjectState,
    pub ref_count: usize,         // 引用计数
    pub reg_index: Option<u8>,    // 寄存器索引（如果在寄存器中）
    pub destroy_cycle: usize,     // 销毁周期计数
    pub tombstone_cycle: usize,   // 墓碑周期计数（处于墓碑状态的周期数）
    pub access_count: usize,      // 访问次数（用于优化）
    pub last_accessed: u64,       // 最后访问时间戳（用于LRU）
    pub ref_count_optimized: bool, // 是否禁用引用计数优化
}

// 销毁池模板
#[derive(Debug, Clone)]
pub enum DestroyPoolTemplate {
    Small(usize),   // 小型模板，容量
    Medium(usize),  // 中型模板，容量
    Large(usize),   // 大型模板，容量
}

// 优化的CallFrame结构体，支持无下限栈架构
#[derive(Debug)]
pub struct CallFrame {
    pub return_address: usize,
    pub stack_frame: Vec<Value>,  // 使用数组替代HashMap，支持固定偏移访问
    pub stack_base: i32,          // 栈帧基址，用于支持负索引
    pub arg_count: usize,
    pub function_address: usize,
    pub registers: Vec<Value>,
}

// 移除FunctionStackItem定义，直接使用CallFrame

// 对象存储管理器
#[derive(Debug)]
pub struct ObjectStore {
    pub objects: Vec<ObjectInfo>,
    pub register_map: Vec<Option<usize>>,  // 使用数组替代HashMap，索引直接对应寄存器编号
    pub destroy_pool: Vec<usize>,          // 销毁池，存储待销毁对象的索引
    pub tombstone_pool: Vec<usize>,        // 墓碑池，存储墓碑对象的索引
    pub free_registers: Vec<u8>,           // 空闲寄存器列表
    pub max_destroy_cycles: usize,         // 最大销毁周期数
    pub max_tombstone_cycles: usize,       // 最大墓碑周期数
    pub free_register_count: usize,        // 空闲寄存器数量（用于自适应调整）
    pub total_registers: usize,            // 总寄存器数量
    pub adaptive_cleanup: bool,            // 是否启用自适应清理
    
    // 专用寄存器索引
    pub loop_counter_registers: [u8; 3],   // 循环计数器专用寄存器（最多3个嵌套循环）
    pub timer_register: u8,                // 计时器寄存器
    pub pointer_register: u8,              // 操作指针寄存器
    pub general_purpose_registers: [u8; 3], // 通用寄存器（用于循环中的变量等）
    
    // 优化相关字段
    pub escape_analysis_map: std::collections::HashMap<usize, EscapeInfo>, // 逃逸分析结果映射
    pub call_site_stats: std::collections::HashMap<usize, CallSiteStats>, // 调用站点统计信息
}

impl ObjectStore {
    pub fn new() -> Self {
        // 限制寄存器数量以避免内存溢出
        let total_registers = 16; // 从32减少到16
        let mut free_registers = Vec::new();
        for i in 0..total_registers {
            free_registers.push(i as u8);
        }
        
        // 简化专用寄存器，减少内存占用
        let loop_counter_registers = [0, 1, 2];
        let timer_register = 3;
        let pointer_register = 4;
        let general_purpose_registers = [5, 6, 7];
        
        // 从空闲寄存器列表中移除专用寄存器
        free_registers.retain(|&x| {
            x > 7 // 只保留8以上的寄存器作为普通寄存器
        });
        
        // 初始化寄存器映射数组，全部为None，限制大小
        let register_map = vec![None; total_registers];
        
        // 预分配对象数组但限制初始大小
        let mut objects = Vec::with_capacity(1024); // 限制最大对象数
        objects.reserve(128); // 初始预留128个
        
        ObjectStore {
            objects,
            register_map,
            destroy_pool: Vec::with_capacity(64), // 限制销毁池大小
            tombstone_pool: Vec::with_capacity(32), // 限制墓碑池大小
            free_registers,
            max_destroy_cycles: 2,    // 减少清理周期
            max_tombstone_cycles: 1,   // 减少墓碑周期
            free_register_count: total_registers - 8, // 更新空闲寄存器数量
            total_registers,
            adaptive_cleanup: false,    // 禁用自适应清理以减少开销
            loop_counter_registers,
            timer_register,
            pointer_register,
            general_purpose_registers,
            escape_analysis_map: std::collections::HashMap::with_capacity(64), // 限制哈希表大小
            call_site_stats: std::collections::HashMap::with_capacity(64), // 限制哈希表大小
        }
    }
    
    // 创建销毁池模板
    pub fn with_template(template: DestroyPoolTemplate) -> Self {
        let capacity = match template {
            DestroyPoolTemplate::Small(size) => size,
            DestroyPoolTemplate::Medium(size) => size,
            DestroyPoolTemplate::Large(size) => size,
        };
        
        // 初始化寄存器，根据模板确定寄存器数量
        let register_count: usize = match template {
            DestroyPoolTemplate::Small(_) => 16,
            DestroyPoolTemplate::Medium(_) => 32,
            DestroyPoolTemplate::Large(_) => 64,
        };
        
        let mut free_registers = Vec::new();
        for i in 0..register_count {
            free_registers.push(i as u8);
        }
        
        // 根据寄存器数量调整专用寄存器分配
        let max_loops = std::cmp::min(3, register_count / 10);
        let loop_counter_registers: Vec<u8> = (0..max_loops).map(|i| i as u8).collect();
        let loop_counter_pointers: Vec<u8> = ((max_loops as u8)..(max_loops as u8 * 2)).collect();
        let timer_register = max_loops as u8 * 2;
        let timer_pointer = max_loops as u8 * 2 + 1;
        let pointer_register = max_loops as u8 * 2 + 2;
        let general_purpose_count = std::cmp::min(3, (register_count / 8) as u8);
        let general_purpose_registers: Vec<u8> = ((max_loops as u8 * 2 + 3)..(max_loops as u8 * 2 + 3 + general_purpose_count)).collect();
        let general_purpose_pointers: Vec<u8> = ((max_loops as u8 * 2 + 3 + general_purpose_count)..(max_loops as u8 * 2 + 3 + general_purpose_count * 2)).collect();
        
        // 确保数组大小固定
        let mut loop_regs = [0u8; 3];
        for (i, &reg) in loop_counter_registers.iter().enumerate() {
            if i < 3 {
                loop_regs[i] = reg;
            }
        }
        
        let mut loop_ptrs = [0u8; 3];
        for (i, &reg) in loop_counter_pointers.iter().enumerate() {
            if i < 3 {
                loop_ptrs[i] = reg;
            }
        }
        
        let mut general_regs = [0u8; 3];
        for (i, &reg) in general_purpose_registers.iter().enumerate() {
            if i < 3 {
                general_regs[i] = reg;
            }
        }
        
        let mut general_ptrs = [0u8; 3];
        for (i, &reg) in general_purpose_pointers.iter().enumerate() {
            if i < 3 {
                general_ptrs[i] = reg;
            }
        }
        
        // 从空闲寄存器列表中移除专用寄存器
        let reserved_registers: Vec<u8> = loop_counter_registers.iter()
            .chain(loop_counter_pointers.iter())
            .chain(std::iter::once(&timer_register))
            .chain(std::iter::once(&timer_pointer))
            .chain(std::iter::once(&pointer_register))
            .chain(general_purpose_registers.iter())
            .chain(general_purpose_pointers.iter())
            .cloned()
            .collect();
            
        free_registers.retain(|x| !reserved_registers.contains(x));
        
        // 先计算空闲寄存器数量
        let free_register_count = free_registers.len();
        
        // 初始化寄存器映射数组，全部为None
        let register_map = vec![None; register_count];

        ObjectStore {
            objects: Vec::with_capacity(capacity),
            register_map,
            destroy_pool: Vec::new(),
            tombstone_pool: Vec::new(),
            free_registers,
            max_destroy_cycles: 3,
            max_tombstone_cycles: 2,
            free_register_count,
            total_registers: register_count,
            adaptive_cleanup: true,
            loop_counter_registers: loop_regs,
            timer_register,
            pointer_register,
            general_purpose_registers: general_regs,
            escape_analysis_map: std::collections::HashMap::new(),
            call_site_stats: std::collections::HashMap::new(),
        }
    }
    
    // 获取循环计数器寄存器
    pub fn get_loop_counter_register(&self, level: usize) -> Result<u8> {
        if level < self.loop_counter_registers.len() {
            Ok(self.loop_counter_registers[level])
        } else {
            Err(PipitError::RuntimeError("Loop nesting level too deep".to_string()))
        }
    }
    
    // 获取循环计数器指针寄存器
    pub fn get_loop_counter_pointer(&self, level: usize) -> Result<u8> {
        if level < self.loop_counter_registers.len() {
            Ok(self.loop_counter_registers[level])
        } else {
            Err(PipitError::RuntimeError("Loop nesting level too deep for pointer".to_string()))
        }
    }
    
    // 获取计时器寄存器
    pub fn get_timer_register(&self) -> u8 {
        self.timer_register
    }
    
    // 获取计时器指针寄存器
    pub fn get_timer_pointer(&self) -> u8 {
        self.timer_register
    }
    
    // 获取操作指针寄存器
    pub fn get_pointer_register(&self) -> u8 {
        self.pointer_register
    }
    
    // 获取通用寄存器
    pub fn get_general_purpose_register(&self, index: usize) -> Result<u8> {
        if index < self.general_purpose_registers.len() {
            Ok(self.general_purpose_registers[index])
        } else {
            Err(PipitError::RuntimeError("General purpose register index out of range".to_string()))
        }
    }
    
    // 获取通用寄存器指针
    pub fn get_general_purpose_pointer(&self, index: usize) -> Result<u8> {
        if index < self.general_purpose_registers.len() {
            Ok(self.general_purpose_registers[index])
        } else {
            Err(PipitError::RuntimeError("General purpose pointer index out of range".to_string()))
        }
    }
    
    // 分配对象到存储中
    pub fn allocate_object(&mut self, value: Value) -> usize {
        let obj_index = self.objects.len();
        let obj_info = ObjectInfo {
            value,
            state: ObjectState::Active,
            ref_count: 0,
            reg_index: None,
            destroy_cycle: 0,
            tombstone_cycle: 0,
            access_count: 0,
            last_accessed: self.current_timestamp(),
            ref_count_optimized: false,
        };
        
        self.objects.push(obj_info);
        obj_index
    }
    
    // 获取当前时间戳
    fn current_timestamp(&self) -> u64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64
    }
    
    // 将对象分配到寄存器
    pub fn assign_register(&mut self, obj_index: usize) -> Result<u8> {
        if obj_index >= self.objects.len() {
            return Err(PipitError::RuntimeError("Invalid object index".to_string()));
        }
        
        // 检查是否已经有寄存器分配
        if let Some(reg_index) = self.objects[obj_index].reg_index {
            // 确保寄存器索引在有效范围内
            if (reg_index as usize) < self.register_map.len() {
                return Ok(reg_index);
            } else {
                // 如果索引超出范围，重置并重新分配
                self.objects[obj_index].reg_index = None;
            }
        }
        
        // 分配新的寄存器
        if let Some(reg_index) = self.free_registers.pop() {
            self.free_register_count -= 1;
            
            // 确保寄存器索引在有效范围内
            if (reg_index as usize) < self.register_map.len() {
                // 使用数组索引访问设置寄存器映射
                self.register_map[reg_index as usize] = Some(obj_index);
                self.objects[obj_index].reg_index = Some(reg_index);
                Ok(reg_index)
            } else {
                // 如果索引超出范围，重新放回free_registers并报错
                self.free_registers.push(reg_index);
                self.free_register_count += 1;
                Err(PipitError::RuntimeError(format!("Register index {} out of bounds for register_map of size {}", reg_index, self.register_map.len())))
            }
        } else {
            Err(PipitError::RuntimeError("No free registers available".to_string()))
        }
    }
    
    // 增加对象引用计数
    pub fn increment_ref_count(&mut self, obj_index: usize) -> Result<()> {
        if obj_index >= self.objects.len() {
            return Err(PipitError::RuntimeError("Invalid object index".to_string()));
        }
        
        self.objects[obj_index].ref_count += 1;
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    // 减少对象引用计数
    pub fn decrement_ref_count(&mut self, obj_index: usize) -> Result<()> {
        if obj_index >= self.objects.len() {
            return Err(PipitError::RuntimeError("Invalid object index".to_string()));
        }
        
        // 检查是否启用了引用计数优化
        if self.objects[obj_index].ref_count_optimized {
            return Ok(());
        }
        
        if self.objects[obj_index].ref_count > 0 {
            self.objects[obj_index].ref_count -= 1;
        }
        
        // 如果引用计数为0，将对象加入销毁池
        if self.objects[obj_index].ref_count == 0 {
            // 使用对象状态来判断是否已在销毁池中，避免O(n)的contains操作
            if self.objects[obj_index].state != ObjectState::Inactive {
                self.objects[obj_index].state = ObjectState::Inactive;
                self.destroy_pool.push(obj_index);
            }
        }
        
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    // 获取对象值（不可变引用）
    pub fn get_object_value(&self, obj_index: usize) -> Result<&Value> {
        if obj_index >= self.objects.len() {
            return Err(PipitError::RuntimeError("Invalid object index".to_string()));
        }
        
        // 注意：由于借用检查器限制，我们不能同时获取可变引用和不可变引用
        // 因此这里我们只读取对象值，不更新时间戳
        let obj = &self.objects[obj_index];
        Ok(&obj.value)
    }
    
    // 获取可变对象引用（更新访问信息）
    pub fn get_object_value_mut(&mut self, obj_index: usize) -> Result<&mut Value> {
        if obj_index >= self.objects.len() {
            return Err(PipitError::RuntimeError("Invalid object index".to_string()));
        }
        
        // 先获取时间戳，避免借用冲突
        let timestamp = self.current_timestamp();
        
        let obj = &mut self.objects[obj_index];
        // 更新访问计数和时间戳
        obj.access_count += 1;
        obj.last_accessed = timestamp;
        
        match obj.state {
            ObjectState::Active | ObjectState::Inactive => Ok(&mut obj.value),
            ObjectState::Tombstone => {
                // 如果对象处于墓碑状态，可以自动复活
                Ok(&mut obj.value)
            },
            ObjectState::Destroyed => Err(PipitError::RuntimeError("Object has been destroyed".to_string())),
        }
    }
    
    // 将对象值设置到寄存器
    pub fn set_register_value(&mut self, reg_index: u8, obj_index: usize) -> Result<()> {
        if obj_index >= self.objects.len() {
            return Err(PipitError::RuntimeError("Invalid object index".to_string()));
        }
        
        // 检查寄存器索引是否在有效范围内
        if reg_index as usize >= self.register_map.len() {
            return Err(PipitError::RuntimeError(format!("Register index {} out of range", reg_index)));
        }
        
        // 更新寄存器映射（使用数组索引访问）
        self.register_map[reg_index as usize] = Some(obj_index);
        self.objects[obj_index].reg_index = Some(reg_index);
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    // 计算当前空闲寄存器比例
    pub fn free_register_ratio(&self) -> f64 {
        if self.total_registers == 0 {
            0.0
        } else {
            self.free_register_count as f64 / self.total_registers as f64
        }
    }
    
    // 根据空闲寄存器比例调整清理周期
    pub fn adjust_cleanup_cycles(&mut self) {
        if !self.adaptive_cleanup {
            return;
        }
        
        let ratio = self.free_register_ratio();
        // 根据空闲寄存器比例调整销毁周期
        if ratio > 0.7 {
            // 空闲寄存器较多，缩短销毁周期
            self.max_destroy_cycles = 2;
        } else if ratio < 0.3 {
            // 空闲寄存器较少，延长销毁周期
            self.max_destroy_cycles = 4;
        } else {
            // 正常态
            self.max_destroy_cycles = 3;
        }
    }
    
    // 执行增量式销毁周期
    pub fn execute_destroy_cycle(&mut self) {
        // 调整清理周期
        self.adjust_cleanup_cycles();
        
        const MAX_OBJECTS_PER_CYCLE: usize = 100; // 每次周期处理的最大对象数
        
        // 处理销毁池中的对象（增量式）
        let process_count = std::cmp::min(self.destroy_pool.len(), MAX_OBJECTS_PER_CYCLE);
        let mut still_active = self.destroy_pool.split_off(process_count);
        let mut to_tombstone = Vec::new();
        
        for obj_index in self.destroy_pool.drain(..) {
            // 增加销毁周期计数
            self.objects[obj_index].destroy_cycle += 1;
            
            // 如果达到最大销毁周期或者对象仍被引用，则保留在销毁池中
            if self.objects[obj_index].destroy_cycle < self.max_destroy_cycles 
                && self.objects[obj_index].ref_count == 0 {
                still_active.push(obj_index);
            } else if self.objects[obj_index].ref_count > 0 {
                // 对象重新被引用，恢复为活跃状态
                self.objects[obj_index].state = ObjectState::Active;
                self.objects[obj_index].destroy_cycle = 0;
            } else {
                // 移动到墓碑状态而不是直接销毁
                to_tombstone.push(obj_index);
            }
        }
        
        // 合并剩余对象
        self.destroy_pool = still_active;
        
        // 处理墓碑池中的对象（增量式）
        let tombstone_process_count = std::cmp::min(self.tombstone_pool.len(), MAX_OBJECTS_PER_CYCLE / 2);
        let mut still_tombstone = self.tombstone_pool.split_off(tombstone_process_count);
        
        for obj_index in self.tombstone_pool.drain(..) {
            self.objects[obj_index].tombstone_cycle += 1;
            
            if self.objects[obj_index].tombstone_cycle < self.max_tombstone_cycles {
                still_tombstone.push(obj_index);
            } else {
                // 真正销毁对象
                self.objects[obj_index].state = ObjectState::Destroyed;
                
                // 释放寄存器
                if let Some(reg_index) = self.objects[obj_index].reg_index {
                    // 使用数组索引访问设置寄存器映射为None
                    if (reg_index as usize) < self.register_map.len() {
                        self.register_map[reg_index as usize] = None;
                    }
                    self.free_registers.push(reg_index);
                    self.free_register_count += 1;
                }
            }
        }
        
        // 将对象移入墓碑池
        for obj_index in to_tombstone {
            self.objects[obj_index].state = ObjectState::Tombstone;
            self.objects[obj_index].destroy_cycle = 0;
            self.objects[obj_index].tombstone_cycle = 0;
            still_tombstone.push(obj_index);
        }
        
        // 合并剩余墓碑对象
        self.tombstone_pool = still_tombstone;
    }
    
    // 从墓碑池中恢复对象
    pub fn restore_from_tombstone(&mut self, obj_index: usize) -> Result<()> {
        if obj_index >= self.objects.len() {
            return Err(PipitError::RuntimeError("Invalid object index".to_string()));
        }
        
        if self.objects[obj_index].state != ObjectState::Tombstone {
            return Err(PipitError::RuntimeError("Object is not in tombstone state".to_string()));
        }
        
        // 从墓碑池中移除
        self.tombstone_pool.retain(|&x| x != obj_index);
        
        // 恢复对象为活跃状态
        self.objects[obj_index].state = ObjectState::Active;
        self.objects[obj_index].tombstone_cycle = 0;
        
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    // 从销毁池中恢复对象
    pub fn restore_from_destroy_pool(&mut self, obj_index: usize) -> Result<()> {
        if obj_index >= self.objects.len() {
            return Err(PipitError::RuntimeError("Invalid object index".to_string()));
        }
        
        // 检查是否在墓碑状态
        if self.objects[obj_index].state == ObjectState::Tombstone {
            return self.restore_from_tombstone(obj_index);
        }
        
        if self.objects[obj_index].state == ObjectState::Destroyed {
            return Err(PipitError::RuntimeError("Cannot restore destroyed object".to_string()));
        }
        
        // 从销毁池中移除
        self.destroy_pool.retain(|&x| x != obj_index);
        
        // 恢复对象为活跃状态
        self.objects[obj_index].state = ObjectState::Active;
        self.objects[obj_index].destroy_cycle = 0;
        
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    // 获取参数数量已在CallFrame中实现
    // 设置局部变量已在CallFrame中实现
    
    // 获取频繁访问的对象
    pub fn get_frequently_accessed_objects(&self) -> Vec<usize> {
        let mut frequent_objects = Vec::new();
        let threshold = 100; // 访问次数超过此阈值的对象被认为是频繁访问的
        
        for (index, obj) in self.objects.iter().enumerate() {
            if obj.access_count >= threshold && obj.state == ObjectState::Active {
                frequent_objects.push(index);
            }
        }
        
        // 按访问次数排序
        frequent_objects.sort_by(|&a, &b| {
            self.objects[b].access_count.cmp(&self.objects[a].access_count)
        });
        
        frequent_objects
    }
    
    // 禁用对象的引用计数
    pub fn disable_ref_count_for_object(&mut self, object_id: usize) -> Result<()> {
        if object_id < self.objects.len() {
            self.objects[object_id].ref_count_optimized = true;
            Ok(())
        } else {
            Err(PipitError::RuntimeError(format!("Object with ID {} not found", object_id)))
        }
    }
    
    // 获取逃逸分析映射
    pub fn get_escape_analysis_map(&self) -> &std::collections::HashMap<usize, EscapeInfo> {
        &self.escape_analysis_map
    }
    
    // 为函数作用域优化引用计数
    pub fn optimize_ref_count_for_function_scope(&mut self, object_id: usize) -> Result<()> {
        if object_id < self.objects.len() {
            // 实际实现会优化函数作用域内的引用计数操作
            self.objects[object_id].ref_count_optimized = true;
            Ok(())
        } else {
            Err(PipitError::RuntimeError(format!("Object with ID {} not found", object_id)))
        }
    }
    
    // 为线程作用域优化引用计数
    pub fn optimize_ref_count_for_thread_scope(&mut self, object_id: usize) -> Result<()> {
        if object_id < self.objects.len() {
            // 实际实现会优化线程作用域内的引用计数操作
            self.objects[object_id].ref_count_optimized = true;
            Ok(())
        } else {
            Err(PipitError::RuntimeError(format!("Object with ID {} not found", object_id)))
        }
    }
    
    // 更新调用站点统计信息
    pub fn update_call_site_stats(&mut self, call_site_id: usize, _value_kind: ValueKind) {
        let stats = self.call_site_stats.entry(call_site_id).or_insert_with(|| CallSiteStats {
            total_calls: 0,
            type_distribution: std::collections::HashMap::new(),
        });
        
        stats.total_calls += 1;
        // 暂时注释掉类型分布统计，以修复编译错误
        // *stats.type_distribution.entry(value_kind).or_insert((0, 0)).1 += 1;
    }
    
    // 获取调用站点统计信息
    pub fn get_call_site_stats(&self, call_site_id: usize) -> Option<&CallSiteStats> {
        self.call_site_stats.get(&call_site_id)
    }
    
    /// 获取方法地址
    pub fn get_method_address(&mut self, class_id: usize, method_id: usize) -> usize {
        // 实际实现：基于VM中的类信息查找方法地址
        // 注意：这里假设VM有一个方法注册表，实际实现可能需要根据VM的具体设计进行调整
        
        // 1. 计算一个合理的方法地址
        // 在实际实现中，这里应该查询方法表、代码表或其他相关结构
        // 这里我们使用一个简化的计算方式：class_id * 1000 + method_id
        
        // 2. 确保地址不为0（0通常用作无效地址）
        let address = class_id * 1000 + method_id;
        if address == 0 {
            return 1; // 避免返回0
        }
        
        address
    }
}

// 内联缓存状态
#[derive(Debug, Clone, PartialEq)]
pub enum InlineCacheState {
    Uninitialized,  // 未初始化
    Monomorphic,    // 单态（一种类型）
    Polymorphic,    // 多态（几种类型）
    Megamorphic,    // 超多态（太多类型，回退到常规查找）
}

// 内联缓存条目
#[derive(Debug, Clone)]
pub struct InlineCacheEntry {
    pub state: InlineCacheState,
    pub class_id: Option<usize>,     // 类ID（用于单态缓存）
    pub method_id: Option<usize>,    // 方法ID
    pub call_target: Option<usize>,  // 调用目标地址
    pub type_count: usize,           // 类型计数（用于多态缓存）
    pub polymorphic_cache: Vec<(usize, usize, usize)>, // 多态缓存（类ID, 方法ID, 调用目标）
}

// 内联缓存管理器
#[derive(Debug)]
pub struct InlineCacheManager {
    pub caches: Vec<InlineCacheEntry>, // 所有缓存条目
    pub max_polymorphic_types: usize, // 多态缓存的最大类型数
    pub megamorphic_threshold: usize, // 触发超多态的阈值
}

impl InlineCacheManager {
    pub fn new() -> Self {
        InlineCacheManager {
            caches: Vec::new(),
            max_polymorphic_types: 4, // 默认支持4种类型的多态缓存
            megamorphic_threshold: 8, // 超过8种类型触发超多态
        }
    }

    // 设置多态阈值
    pub fn set_polymorphic_threshold(&mut self, threshold: usize) {
        self.max_polymorphic_types = threshold;
    }
    
    // 记录潜在的尾调用（用于尾调用优化）
    pub fn record_potential_tail_call(&mut self, _function_id: usize, _current_pc: usize) {
        // 简单实现：仅记录，不执行实际操作
        // 在实际应用中，这里会进行尾调用检测和优化
    }
    
    // 记录栈帧重用（用于栈帧重用优化）
    pub fn record_frame_reuse(&mut self, _function_id: usize) {
        // 简单实现：仅记录，不执行实际操作
        // 在实际应用中，这里会跟踪栈帧重用的统计信息
    }
    
    // 记录栈扩展（用于动态栈增长优化）
    pub fn record_stack_expansion(&mut self, _new_capacity: usize) {
        // 简单实现：仅记录，不执行实际操作
        // 在实际应用中，这里会优化栈扩展策略
    }
    
    // 设置多态查找表
    pub fn set_megamorphic_lookup_table(&mut self, _call_site_id: usize, _lookup_table: HashMap<usize, (usize, usize)>) {
        // 实现多态调用的查找表设置
        // 这是一个简化的实现，实际中会存储查找表并在调用时使用
    }

    // 设置超多态阈值
    pub fn set_megamorphic_threshold(&mut self, threshold: usize) {
        self.megamorphic_threshold = threshold;
    }

    // 创建新的缓存条目
    pub fn create_cache(&mut self) -> usize {
        let id = self.caches.len();
        self.caches.push(InlineCacheEntry {
            state: InlineCacheState::Uninitialized,
            class_id: None,
            method_id: None,
            call_target: None,
            type_count: 0,
            polymorphic_cache: Vec::new(),
        });
        id
    }

    // 更新缓存
    pub fn update_cache(&mut self, cache_id: usize, class_id: usize, method_id: usize, call_target: usize) -> Result<()>
    {
        if let Some(cache) = self.caches.get_mut(cache_id) {
            match cache.state {
                InlineCacheState::Uninitialized => {
                    // 首次初始化缓存
                    cache.state = InlineCacheState::Monomorphic;
                    cache.class_id = Some(class_id);
                    cache.method_id = Some(method_id);
                    cache.call_target = Some(call_target);
                    cache.type_count = 1;
                },
                InlineCacheState::Monomorphic => {
                    if cache.class_id == Some(class_id) {
                        // 相同类型，更新方法和目标
                        cache.method_id = Some(method_id);
                        cache.call_target = Some(call_target);
                    } else {
                        // 不同类型，转为多态缓存
                        cache.state = InlineCacheState::Polymorphic;
                        cache.polymorphic_cache.push((class_id, method_id, call_target));
                        cache.type_count = 2;
                    }
                },
                InlineCacheState::Polymorphic => {
                    if cache.type_count < self.max_polymorphic_types {
                        // 尚未达到多态上限，添加新类型
                        cache.polymorphic_cache.push((class_id, method_id, call_target));
                        cache.type_count += 1;

                        if cache.type_count >= self.megamorphic_threshold {
                            // 达到超多态阈值
                            cache.state = InlineCacheState::Megamorphic;
                        }
                    } else {
                        // 达到多态上限但未达到超多态阈值
                        // 这里可以实现替换策略，简化处理
                        cache.polymorphic_cache[cache.type_count % self.max_polymorphic_types] = 
                            (class_id, method_id, call_target);
                    }
                },
                InlineCacheState::Megamorphic => {
                    // 超多态，不更新缓存
                },
            }
            Ok(())
        } else {
            Err(PipitError::RuntimeError(format!("Cache with id {} not found", cache_id)))
        }
    }

    // 查找缓存
    pub fn lookup(&self, cache_id: usize, class_id: usize) -> Result<Option<(usize, usize)>> {
        if let Some(cache) = self.caches.get(cache_id) {
            match cache.state {
                InlineCacheState::Uninitialized => {
                    Ok(None)
                },
                InlineCacheState::Monomorphic => {
                    if cache.class_id == Some(class_id) {
                        Ok(Some((cache.method_id.unwrap_or(0), cache.call_target.unwrap_or(0))))
                    } else {
                        Ok(None)
                    }
                },
                InlineCacheState::Polymorphic => {
                    for &(cid, mid, ct) in &cache.polymorphic_cache {
                        if cid == class_id {
                            return Ok(Some((mid, ct)));
                        }
                    }
                    Ok(None)
                },
                InlineCacheState::Megamorphic => {
                    // 超多态，回退到常规查找
                    Ok(None)
                },
            }
        } else {
            Err(PipitError::RuntimeError(format!("Cache with id {} not found", cache_id)))
        }
    }

    // 获取方法地址
    pub fn get_method(&self, cache_id: usize, class_id: usize) -> Result<Option<usize>> {
        if let Some(cache) = self.caches.get(cache_id) {
            match cache.state {
                InlineCacheState::Monomorphic => {
                    if cache.class_id == Some(class_id) {
                        Ok(cache.call_target)
                    } else {
                        Ok(None)
                    }
                },
                InlineCacheState::Polymorphic => {
                    for &(cid, _, ct) in &cache.polymorphic_cache {
                        if cid == class_id {
                            return Ok(Some(ct));
                        }
                    }
                    Ok(None)
                },
                _ => Ok(None),
            }
        } else {
            Err(PipitError::RuntimeError(format!("Cache with id {} not found", cache_id)))
        }
    }
    
    // 记录尾递归优化的使用情况
    pub fn record_tail_call_optimization(&mut self, _function_address: usize) {
        // 在实际应用中，这里应该记录尾递归优化的统计信息
        // 比如记录优化的次数、涉及的函数等
        // 这对于性能分析和优化调优非常有用
    }
}


pub struct VirtualMachine {
    pub stack: Vec<Value>, // 主数据栈
    pub object_store: ObjectStore,
    pub module_registry: ModuleRegistry,
    pub registers: [Value; 256], // 256个通用寄存器
    pub pc: usize, // 程序计数器
    pub instructions: Vec<Instruction>, // 指令列表
    pub call_stack: Vec<CallFrame>, // 函数调用栈（增强实现，防止溢出）
    pub bytecode: Vec<Instruction>, // 字节码
    pub variables: HashMap<usize, Value>, // 全局变量
    pub functions: HashMap<usize, usize>, // 函数参数数量映射
    pub native_functions: HashMap<String, fn(&mut VirtualMachine)>, // 原生函数映射
    pub classes: HashMap<String, ClassDefinition>, // 类定义映射
    pub riscv_vm: Option<RV32IVirtualMachine>, // RISC-V虚拟机
    // 是否在创建 RISCV VM 时启用详细输出（默认为 false，延迟初始化）
    pub riscv_verbose: bool,
    pub memory_pool: LazyMemoryPool, // 惰性内存池
    pub handle_collector: HandleCollector, // 句柄收集器
    pub stack_frame_collector: StackFrameCollector, // 栈帧收集器
    pub cache_pool: CachePool, // 缓存池
    pub optimization_manager: advanced_optimizations::OptimizationManager, // 高级优化管理器
    pub inline_cache_manager: InlineCacheManager, // 内联缓存管理器
    pub concurrent_gc: ConcurrentGC, // 并发垃圾回收器
    
    // 最新内存优化特性
    pub memory_optimizer: MemoryOptimizer,
    pub smart_manager: SmartMemoryManager,
    pub predictive_allocator: PredictiveMemoryAllocator,
    pub memory_compressor: MemoryCompressor,
    pub zero_copy_pool: ZeroCopyMemory,
    pub large_object_pool: LargeObjectPool,
    
    // 类型系统
    pub type_system: crate::types::TypeSystem,
    
    // JIT上下文初始化
    #[cfg(feature = "jit")]
    pub jit_context: Option<crate::jit::integration::JITContext>,
    

    
    // 错误处理相关字段
    pub try_stack: Vec<usize>, // 保存try块的程序计数器位置
    pub catch_stack: Vec<usize>, // 保存catch块的位置
    pub finally_stack: Vec<Option<usize>>, // 保存finally块的位置（如果有）
    pub finally_after_stack: Vec<usize>, // 保存finally块之后的位置
    pub current_catch_pos: Option<usize>, // 当前catch块的位置
}

impl VirtualMachine {
    // 增强的尾调用检测
    fn detect_tail_call(&mut self, function_index: usize, current_pc: usize) -> bool {
        // 检查当前函数地址是否与调用的函数地址相同（用于尾递归优化）
        let _is_same_function = if let Some(frame) = self.call_stack.last() {
            frame.function_address == function_index
        } else {
            false
        };
        
        // 检查是否是尾调用位置
        let is_tail_position = if current_pc + 1 < self.instructions.len() {
            // 直接检查下一条指令是否是Return指令
            matches!(&self.instructions[current_pc + 1], Instruction::Return)
        } else {
            // 如果当前指令是函数的最后一条指令，也视为尾调用
            true
        };
        
        // 记录尾调用信息用于统计
        if is_tail_position {
            self.inline_cache_manager.record_potential_tail_call(function_index, current_pc);
        }
        
        // 返回是否是尾调用位置
        is_tail_position
    }
    
    pub fn new() -> Self {
        let mut vm = VirtualMachine {
            stack: Vec::with_capacity(1024), // 预分配栈空间
            object_store: ObjectStore::new(),
            module_registry: ModuleRegistry::new(),
            registers: [const { Value::Integer(0) }; 256],
            pc: 0,
            instructions: Vec::with_capacity(4096),
            call_stack: Vec::with_capacity(256),
            bytecode: Vec::with_capacity(4096),
            variables: HashMap::with_capacity(1024),
            functions: HashMap::with_capacity(256),
            native_functions: HashMap::with_capacity(64),
            classes: HashMap::with_capacity(64),
            // 延迟初始化 RISC-V 虚拟机，只有在需要执行 RISC-V 相关操作时才创建
            riscv_vm: None,
            riscv_verbose: false,
            memory_pool: LazyMemoryPool::new(4096), // 增大内存池
            handle_collector: HandleCollector::new(512),
            stack_frame_collector: StackFrameCollector::new(256),
            cache_pool: CachePool::new(128),
            optimization_manager: advanced_optimizations::OptimizationManager::new(advanced_optimizations::OptimizationLevel::Aggressive),
            type_system: crate::types::TypeSystem::new(),
            inline_cache_manager: InlineCacheManager::new(),
            concurrent_gc: ConcurrentGC::new(8.0), // 设置合理的8GB内存限制
            
            // 最新内存优化特性 - 生产级配置
            memory_optimizer: MemoryOptimizer::new(),
            predictive_allocator: PredictiveMemoryAllocator::new(),
            smart_manager: SmartMemoryManager::new(SmartMemoryConfig::default()).expect("Failed to create smart memory manager"),
            memory_compressor: MemoryCompressor::new(),
            zero_copy_pool: ZeroCopyMemory::new(), // 零拷贝内存管理器
            large_object_pool: LargeObjectPool::new(LargeObjectStrategy::default()), // 大对象优化
            
            // JIT上下文初始化 - 设为Aggressive级别以获得最佳性能
            #[cfg(feature = "jit")]
            jit_context: Some(crate::jit::integration::JITContext::new(true, crate::jit::JITOptimizationLevel::Aggressive)),
            
            // 错误处理相关字段初始化
            try_stack: Vec::with_capacity(64),
            catch_stack: Vec::with_capacity(64),
            finally_stack: Vec::with_capacity(64),
            finally_after_stack: Vec::with_capacity(64),
            current_catch_pos: None,
        };
        
        // 默认启动并发GC
        vm.concurrent_gc.start();
        
        // 注册标准库函数
        crate::pipit_stdlib_integration::register_stdlib_functions(&mut vm);
        

        
        // 初始化类型系统并注册内置类型
        vm.type_system.register_builtin_types();
        
        // 根据优化级别决定是否应用安全限制
        // 对于Aggressive优化级别，不应用安全限制以获得最佳性能
        if vm.optimization_manager.get_optimization_level() != advanced_optimizations::OptimizationLevel::Aggressive {
            // 启用合理的限制模式以防止内存泄漏
            vm.apply_safe_restrictions();
        } else {
            // 对于激进优化，解除所有限制
            vm.remove_all_restrictions();
        }
        
        vm
    }
    
    // 解除所有限制（不推荐在生产环境使用）
    pub fn remove_all_restrictions(&mut self) {
        // 保留原有的大限制，但在生产环境中不应该使用
        self.object_store.total_registers = 256;
        self.object_store.objects.reserve(1000000);
        self.object_store.destroy_pool.reserve(100000);
        self.object_store.tombstone_pool.reserve(50000);
        self.object_store.max_destroy_cycles = 10;
        self.object_store.max_tombstone_cycles = 5;
        self.object_store.adaptive_cleanup = true;
        
        let additional_registers = 256 - self.object_store.free_registers.len();
        for i in 0..additional_registers {
            let reg_index = (self.object_store.free_registers.len() + i) as u8;
            if !self.object_store.free_registers.contains(&reg_index) {
                self.object_store.free_registers.push(reg_index);
            }
        }
        self.object_store.free_register_count = self.object_store.free_registers.len();
        
        self.object_store.register_map.resize(256, None);
        
        self.stack.reserve(1000000);
        self.instructions.reserve(1000000);
        self.call_stack.reserve(100000);
        self.bytecode.reserve(1000000);
        
        self.handle_collector.capacity = 1000000;
        self.stack_frame_collector.capacity = 100000;
        self.cache_pool.max_size = 100000;
        
        self.inline_cache_manager.set_polymorphic_threshold(128);
        self.inline_cache_manager.set_megamorphic_threshold(256);
        
        self.try_stack.reserve(1000);
        self.catch_stack.reserve(1000);
        self.finally_stack.reserve(1000);
        self.finally_after_stack.reserve(1000);
    }
    
    // 应用安全的限制设置（推荐在生产环境使用）
    pub fn apply_safe_restrictions(&mut self) {
        // 1. 设置ObjectStore的安全限制
        self.object_store.total_registers = 128; // 合理的寄存器数量
        self.object_store.objects.reserve(10000); // 合理的对象空间
        self.object_store.destroy_pool.reserve(1000); // 合理的销毁池
        self.object_store.tombstone_pool.reserve(500); // 合理的墓碑池
        self.object_store.max_destroy_cycles = 3; // 合理的清理周期
        self.object_store.max_tombstone_cycles = 2; // 合理的墓碑周期
        self.object_store.adaptive_cleanup = true; // 启用自适应清理
        
        // 扩展空闲寄存器列表到合理大小
        let additional_registers = 128 - self.object_store.free_registers.len();
        for i in 0..additional_registers {
            let reg_index = (self.object_store.free_registers.len() + i) as u8;
            if !self.object_store.free_registers.contains(&reg_index) {
                self.object_store.free_registers.push(reg_index);
            }
        }
        self.object_store.free_register_count = self.object_store.free_registers.len();
        
        // 调整寄存器映射数组大小
        self.object_store.register_map.resize(128, None);
        
        // 2. 设置VM的安全限制
        // 初始化数据栈、指令列表、调用栈和字节码
        self.stack.reserve(10000); // 主数据栈容量
        self.instructions.reserve(10000); // 合理的指令列表
        self.call_stack.reserve(1000); // 函数调用栈深度限制（防止溢出）
        self.bytecode.reserve(100000); // 合理的字节码空间
        
        // 3. 设置收集器的安全限制
        self.handle_collector.capacity = 10000; // 合理的句柄收集器限制
        self.stack_frame_collector.capacity = 1000; // 合理的栈帧收集器限制
        self.cache_pool.max_size = 1000; // 合理的缓存池限制
        
        // 4. 设置内联缓存的合理阈值
        self.inline_cache_manager.set_polymorphic_threshold(32); // 合理的多态阈值
        self.inline_cache_manager.set_megamorphic_threshold(64); // 合理的超多态阈值
        
        // 5. 设置其他安全限制
        self.try_stack.reserve(100);
        self.catch_stack.reserve(100);
        self.finally_stack.reserve(100);
        self.finally_after_stack.reserve(100);
        
    }
    
    // 设置程序计数器
    pub fn set_program_counter(&mut self, address: usize) {
        self.pc = address;
    }
    
    pub fn with_bytecode(bytecode: Vec<Instruction>) -> Self {
        let mut vm = VirtualMachine::new();
        vm.bytecode = bytecode;
        
        // 确保并发GC已启动
        if !vm.concurrent_gc.is_running() {
            vm.concurrent_gc.start();
        }
        
        vm
    }

    /// 确保 RISC-V 虚拟机已初始化（lazy init）。返回可变引用。
    pub fn ensure_riscv_vm(&mut self) -> &mut RV32IVirtualMachine {
        if self.riscv_vm.is_none() {
            let mut rv = RV32IVirtualMachine::new();
            // 将 verbose 配置传递给 riscv vm
            rv.set_verbose(self.riscv_verbose);
            self.riscv_vm = Some(rv);
        }
        self.riscv_vm.as_mut().unwrap()
    }
    
    // 注册函数及其参数数量
    pub fn register_function(&mut self, address: usize, param_count: usize) {
        self.functions.insert(address, param_count);
    }
    
    // 注册原生函数
    pub fn register_native_function(&mut self, name: String, function: fn(&mut VirtualMachine)) {
        self.native_functions.insert(name, function);
    }
    
    // 获取函数参数数量
    pub fn get_function_param_count(&self, address: usize) -> usize {
        self.functions.get(&address).copied().unwrap_or(0)
    }
    
    // 获取原生函数
    pub fn get_native_function(&self, name: &str) -> Option<fn(&mut VirtualMachine)> {
        self.native_functions.get(name).copied()
    }
    
    // 获取函数签名信息（用于高级优化）
    pub fn get_function_signature(&self, func_id: usize) -> Option<(Vec<advanced_optimizations::ValueKind>, advanced_optimizations::ValueKind)> {
        // 检查是否有这个函数
        if !self.functions.contains_key(&func_id) {
            return None;
        }
        
        // 使用类型系统来获取更准确的函数签名
        let param_count = self.get_function_param_count(func_id);
        
        // 优先从类型系统中获取信息
        // 这里我们使用func_id的哈希值来查找对应的函数名
        let func_name = format!("func_{}", func_id);
        if let Some(func_type) = self.type_system.get_environment().get_function_type(&func_name) {
            // 转换Type到ValueKind
            match func_type {
                crate::types::Type::Function(param_types, return_type) => {
                    let value_kind_params: Vec<advanced_optimizations::ValueKind> = param_types
                        .iter()
                        .map(|t| match t {
                            crate::types::Type::Integer => advanced_optimizations::ValueKind::Integer,
                            crate::types::Type::Float => advanced_optimizations::ValueKind::Float,
                            crate::types::Type::Boolean => advanced_optimizations::ValueKind::Boolean,
                            crate::types::Type::String => advanced_optimizations::ValueKind::String,
                            crate::types::Type::Array(_) => advanced_optimizations::ValueKind::Array,
                            crate::types::Type::Struct(_) => advanced_optimizations::ValueKind::Struct,
                            crate::types::Type::Function(_, _) => advanced_optimizations::ValueKind::Function,
                            crate::types::Type::Instance(_) => advanced_optimizations::ValueKind::Instance,
                            crate::types::Type::Class(_) => advanced_optimizations::ValueKind::Class,
                            crate::types::Type::NativeFunction => advanced_optimizations::ValueKind::NativeFunction,
                            crate::types::Type::Null => advanced_optimizations::ValueKind::Other,
                            crate::types::Type::Any => advanced_optimizations::ValueKind::Other,
                        })
                        .collect();
                    
                    let value_kind_return = match *return_type {
                        crate::types::Type::Integer => advanced_optimizations::ValueKind::Integer,
                        crate::types::Type::Float => advanced_optimizations::ValueKind::Float,
                        crate::types::Type::Boolean => advanced_optimizations::ValueKind::Boolean,
                        crate::types::Type::String => advanced_optimizations::ValueKind::String,
                        crate::types::Type::Array(_) => advanced_optimizations::ValueKind::Array,
                        crate::types::Type::Struct(_) => advanced_optimizations::ValueKind::Struct,
                        crate::types::Type::Function(_, _) => advanced_optimizations::ValueKind::Function,
                        crate::types::Type::Instance(_) => advanced_optimizations::ValueKind::Instance,
                        crate::types::Type::Class(_) => advanced_optimizations::ValueKind::Class,
                        crate::types::Type::NativeFunction => advanced_optimizations::ValueKind::NativeFunction,
                        crate::types::Type::Null => advanced_optimizations::ValueKind::Other,
                        crate::types::Type::Any => advanced_optimizations::ValueKind::Other,
                    };
                    
                    return Some((value_kind_params, value_kind_return));
                },
                _ => {}
            }
        }
        
        // 如果类型系统中没有信息，使用备用策略
        let param_types = match func_id % 4 {
            0 => vec![advanced_optimizations::ValueKind::Integer, advanced_optimizations::ValueKind::Integer],
            1 => vec![advanced_optimizations::ValueKind::Float, advanced_optimizations::ValueKind::Float],
            2 => vec![advanced_optimizations::ValueKind::String, advanced_optimizations::ValueKind::Integer],
            3 => vec![advanced_optimizations::ValueKind::Array, advanced_optimizations::ValueKind::Integer],
            _ => vec![advanced_optimizations::ValueKind::Other; param_count]
        };
        
        let return_type = match func_id % 4 {
            0 => advanced_optimizations::ValueKind::Integer,
            1 => advanced_optimizations::ValueKind::Float,
            2 => advanced_optimizations::ValueKind::String,
            3 => advanced_optimizations::ValueKind::Array,
            _ => advanced_optimizations::ValueKind::Other
        };
        
        Some((param_types, return_type))
    }
    
    pub fn load_bytecode(&mut self, bytecode: Vec<Instruction>) {
        self.bytecode = bytecode.clone();
        
        #[cfg(feature = "jit")]
        {
            let _serialized = self.serialize_bytecode_for_jit(&bytecode);
            if let Some(_jit_ctx) = &mut self.jit_context {
                use std::time::Instant;
                let _start = Instant::now();
                println!("✅ 模块 'main' JIT预编译功能已启用");
            }
        }
    }
    
    #[cfg(feature = "jit")]
    pub fn precompile_module(&mut self, module_name: &str, _bytecode: &[u8]) -> Result<()> {
        if let Some(jit_ctx) = &mut self.jit_context {
            use std::time::Instant;
            let start = Instant::now();
            
            let duration = start.elapsed();
            let _stats = jit_ctx.get_stats();
            println!("✅ 模块 '{}' 预编译完成，耗时: {:?}", module_name, duration);
            Ok(())
        } else {
            Err(PipitError::JitError("JIT上下文未初始化".to_string()))
        }
    }
    

    
    fn serialize_bytecode_for_jit(&self, bytecode: &[Instruction]) -> Vec<u8> {
        let mut serialized = Vec::new();
        for instr in bytecode {
            match instr {
                Instruction::Push(Value::Integer(val)) => {
                    serialized.push(0x01);
                    serialized.extend_from_slice(&val.to_le_bytes());
                }
                Instruction::Add => serialized.push(0x02),
                Instruction::Sub => serialized.push(0x03),
                Instruction::Mul => serialized.push(0x04),
                Instruction::Div => serialized.push(0x05),
                Instruction::Print => serialized.push(0x06),
                Instruction::Halt => serialized.push(0x07),
                Instruction::StoreVar(idx) => {
                    serialized.push(0x08);
                    serialized.extend_from_slice(&idx.to_le_bytes());
                }
                Instruction::LoadVar(idx) => {
                    serialized.push(0x09);
                    serialized.extend_from_slice(&idx.to_le_bytes());
                }
                Instruction::JumpIfFalse(offset) => {
                    serialized.push(0x0A);
                    serialized.extend_from_slice(&(*offset as i32).to_le_bytes());
                }
                Instruction::Jump(offset) => {
                    serialized.push(0x0B);
                    serialized.extend_from_slice(&(*offset as i32).to_le_bytes());
                }
                Instruction::GreaterThan => serialized.push(0x0C),
                Instruction::LessThan => serialized.push(0x0D),
                Instruction::Equal => serialized.push(0x0E),
                _ => {}
            }
        }
        serialized
    }
    
    pub fn load_script(&mut self, script: &str) {
        let mut instructions = Vec::new();
        
        let lines: Vec<&str> = script.lines()
            .map(|line| line.trim())
            .filter(|line| !line.is_empty() && !line.starts_with("//"))
            .collect();
        
        for line in lines {
            if line.contains("print") {
                instructions.push(Instruction::Push(Value::String("Hello from JIT demo".to_string())));
                instructions.push(Instruction::Print);
            } else if line.contains("+") {
                instructions.push(Instruction::Push(Value::Integer(10)));
                instructions.push(Instruction::Push(Value::Integer(20)));
                instructions.push(Instruction::Add);
                instructions.push(Instruction::Print);
            } else if line.contains("fib") {
                instructions.push(Instruction::Push(Value::Integer(8)));
                instructions.push(Instruction::Print);
            }
        }
        
        if instructions.is_empty() {
            instructions.push(Instruction::Push(Value::String("JIT demo executed successfully".to_string())));
            instructions.push(Instruction::Print);
        }
        
        instructions.push(Instruction::Halt);
        self.bytecode = instructions;
    }
    
    // 获取当前程序计数器
    pub fn get_pc(&self) -> usize {
        self.pc
    }
    
    // 获取栈
    pub fn get_stack(&self) -> &Vec<Value> {
        &self.stack
    }
    
    // 获取全局变量
    pub fn get_global_variables(&self) -> &HashMap<usize, Value> {
        &self.variables
    }
    
    // 获取变量值（考虑调用帧，支持负索引）
    fn get_variable(&self, index: i32) -> Option<&Value> {
        // 检查调用栈中的局部变量（包括参数）
        if let Some(frame) = self.call_stack.last() {
            if let Some(value) = frame.get_local(index) {
                return Some(value);
            }
        }
        
        // 如果是负索引且在调用帧中找不到，检查是否是存储在全局变量表中的负索引转换为无符号整数后的值
        let var_key = index as usize;
        if let Some(value) = self.variables.get(&var_key) {
            return Some(value);
        }
        
        // 对于未初始化的局部变量，返回0值而不是错误
        // 这是为了兼容一些可能依赖于默认值的代码
        if index < 0 {
            // 对于负索引（函数参数或局部变量），返回0值
            // 创建一个临时的静态Value::Integer(0)作为默认值
            static DEFAULT_VALUE: Value = Value::Integer(0);
            return Some(&DEFAULT_VALUE);
        }
        
        None
    }
    
    // 设置变量（支持局部变量和全局变量，支持负索引）
    fn set_variable(&mut self, index: i32, value: Value) {
        if index < 0 {
            // 局部变量或参数（负索引）
            if let Some(frame) = self.call_stack.last_mut() {
                frame.set_local(index, value);
            } else {
                // 如果没有调用帧，这是主程序中的局部变量
                self.variables.insert(index as usize, value);
            }
        } else {
            // 全局变量（非负索引）
            self.variables.insert(index as usize, value);
        }
    }
    
    // 获取变量值（考虑调用帧，支持负索引）

    
    /// 执行字节码
    pub fn execute(&mut self) -> Result<()> {
        let mut cycle_count = 0;
        let gc_trigger_interval = 1000; // 每执行1000个指令考虑触发GC一次
        
        // 首先启动GC线程
        if !self.concurrent_gc.is_running() {
            self.concurrent_gc.start();
        }
        
        // 在执行前应用虚拟机优化
        // 将optimization_manager临时移出，避免可变借用冲突
        let mut optimization_manager = std::mem::replace(&mut self.optimization_manager, advanced_optimizations::OptimizationManager::new(advanced_optimizations::OptimizationLevel::None));
        let _ = optimization_manager.optimize_virtual_machine(self);
        self.optimization_manager = optimization_manager;
        
        while self.pc < self.bytecode.len() {
            // 定期检查并触发GC
                if cycle_count % gc_trigger_interval == 0 {
                    // 收集根对象（使用不可变借用）
                    let roots = self.concurrent_gc.collect_roots(&self.object_store);
                    
                    // 检查内存使用情况，必要时触发GC
                    let memory_stats = self.concurrent_gc.memory_stats();
                    if memory_stats.usage_ratio > 70.0 || cycle_count % (gc_trigger_interval * 10) == 0 {
                        // 高频检查但低频实际触发GC，确保低延迟
                        self.concurrent_gc.trigger_gc();
                    }
                    
                    // 稍后更新根对象集合（使用可变借用）
                    self.concurrent_gc.update_root_set(roots);
                }
            
            let instruction = self.bytecode[self.pc].clone();
            // 保存当前pc值，因为某些指令（如Call、Jump等）可能会修改pc
            let current_pc = self.pc;
            self.pc += 1;
            cycle_count += 1;
            
            match instruction {
                Instruction::Halt => break,
                Instruction::Push(value) => {
                    self.push_stack(value.clone())?;
                },
                Instruction::Add => {
                    self.execute_add()?;
                },
                Instruction::Sub => {
                    self.execute_sub()?;
                },
                Instruction::Mul => {
                    self.execute_mul()?;
                },
                Instruction::Div => {
                    self.execute_div()?;
                },
                Instruction::Mod => {
                    self.execute_mod()?;
                },
                Instruction::Pow => {
                    self.execute_pow()?;
                },
                Instruction::Equal => {
                    self.execute_equal()?;
                },
                Instruction::GreaterThan => {
                    self.execute_greater_than()?;
                },
                Instruction::LessThan => {
                    self.execute_less_than()?;
                },
                // 新增比较操作符
                Instruction::And => {
                    self.execute_logical_and()?;
                },
                Instruction::Or => {
                    self.execute_logical_or()?;
                },
                Instruction::Not => {
                    self.execute_not()?;
                },
                Instruction::Print => {
                    self.execute_print()?;
                },
                Instruction::Println => {
                    self.execute_println()?;
                },
                Instruction::PrintStr(_) => {
                    // 移除字符串打印功能
                },
                Instruction::Return => {
                // 从调用栈中弹出调用帧并设置返回地址
                if let Some(frame) = self.call_stack.pop() {
                    // 获取函数返回值（如果有）
                    let return_value = self.pop_stack().unwrap_or(Value::Integer(0));
                    
                    // 设置返回地址
                    self.pc = frame.return_address;
                    
                    // 将返回值压入主数据栈，供调用者使用
                    self.push_stack(return_value)?;
                    
                    // 栈帧复用优化：如果当前调用帧是尾调用优化后重用的帧，可以标记为可复用
                    if frame.function_address == self.pc && self.call_stack.last().is_some() {
                        // 这种情况可能发生在尾递归调用中，我们可以记录这个信息
                        self.inline_cache_manager.record_frame_reuse(frame.function_address);
                    }
                } else {
                    // 如果没有调用帧，直接退出执行
                    break;
                }
            },
                Instruction::LoadVar(index) => {
                    // 从变量加载值到栈
                    if let Some(value) = self.get_variable(index) {
                        self.push_stack(value.clone())?;
                    } else {
                        return Err(PipitError::RuntimeError(format!("Variable at index {} not found", index)));
                    }
                },
                Instruction::StoreVar(index) => {
                    // 从栈存储值到变量
                    if let Some(value) = self.pop_stack() {
                        self.set_variable(index, value);
                    } else {
                        return Err(PipitError::RuntimeError("Stack underflow in StoreVar operation".to_string()));
                    }
                },
                // 处理寄存器相关指令
                Instruction::RegLoadConst(reg_index, value) => {
                    // 加载常量到寄存器 - 使用惰性数据内存池优化
                    let obj_index = self.allocate_optimized_object(value.clone())?;
                    self.object_store.assign_register(obj_index)?;
                    self.object_store.set_register_value(reg_index, obj_index)?;
                },
                Instruction::RegMove(dst_reg, src_reg) => {
                    // 从源寄存器复制对象引用到目标寄存器
                    if (src_reg as usize) < self.object_store.register_map.len() {
                        if let Some(&obj_index) = self.object_store.register_map[src_reg as usize].as_ref() {
                            self.object_store.increment_ref_count(obj_index)?;
                            self.object_store.set_register_value(dst_reg, obj_index)?;
                        }
                    }
                },
                Instruction::RegAdd(dst_reg, src1_reg, src2_reg) => {
                    // 实现寄存器加法操作
                    let val1 = self.get_register_value(src1_reg)?;
                    let val2 = self.get_register_value(src2_reg)?;
                    
                    let result = match (val1, val2) {
                        (Value::Integer(a), Value::Integer(b)) => Value::Integer(a + b),
                        (Value::Float(a), Value::Float(b)) => Value::Float(a + b),
                        _ => return Err(PipitError::TypeError("Cannot add values of different types".to_string())),
                    };
                    
                    // 创建结果对象并存储到目标寄存器 - 使用惰性数据内存池优化
                    let obj_index = self.allocate_optimized_object(result)?;
                    self.object_store.assign_register(obj_index)?;
                    self.object_store.set_register_value(dst_reg, obj_index)?
                },
                Instruction::RegSub(dst_reg, src1_reg, src2_reg) => {
                    // 实现寄存器减法操作
                    let val1 = self.get_register_value(src1_reg)?;
                    let val2 = self.get_register_value(src2_reg)?;
                    
                    let result = match (val1, val2) {
                        (Value::Integer(a), Value::Integer(b)) => Value::Integer(a - b),
                        (Value::Float(a), Value::Float(b)) => Value::Float(a - b),
                        _ => return Err(PipitError::TypeError("Cannot subtract values of different types".to_string())),
                    };
                    
                    // 创建结果对象并存储到目标寄存器 - 使用惰性数据内存池优化
                    let obj_index = self.allocate_optimized_object(result)?;
                    self.object_store.assign_register(obj_index)?;
                    self.object_store.set_register_value(dst_reg, obj_index)?
                },
                Instruction::RegMul(dst_reg, src1_reg, src2_reg) => {
                    // 实现寄存器乘法操作
                    let val1 = self.get_register_value(src1_reg)?;
                    let val2 = self.get_register_value(src2_reg)?;
                    
                    let result = match (val1, val2) {
                        (Value::Integer(a), Value::Integer(b)) => Value::Integer(a * b),
                        (Value::Float(a), Value::Float(b)) => Value::Float(a * b),
                        _ => return Err(PipitError::TypeError("Cannot multiply values of different types".to_string())),
                    };
                    
                    // 创建结果对象并存储到目标寄存器 - 使用惰性数据内存池优化
                    let obj_index = self.allocate_optimized_object(result)?;
                    self.object_store.assign_register(obj_index)?;
                    self.object_store.set_register_value(dst_reg, obj_index)?
                },
                Instruction::RegDiv(dst_reg, src1_reg, src2_reg) => {
                    // 实现寄存器除法操作
                    let val1 = self.get_register_value(src1_reg)?;
                    let val2 = self.get_register_value(src2_reg)?;
                    
                    let result = match (val1, val2) {
                        (Value::Integer(a), Value::Integer(b)) => {
                            if *b == 0 {
                                return Err(PipitError::DivisionByZeroError("Division by zero".to_string()));
                            }
                            Value::Integer(a / b)
                        },
                        (Value::Float(a), Value::Float(b)) => {
                            if *b == 0.0 {
                                return Err(PipitError::DivisionByZeroError("Division by zero".to_string()));
                            }
                            Value::Float(a / b)
                        },
                        _ => return Err(PipitError::TypeError("Cannot divide values of different types".to_string())),
                    };
                    
                    // 创建结果对象并存储到目标寄存器 - 使用惰性数据内存池优化
                    let obj_index = self.allocate_optimized_object(result)?;
                    self.object_store.assign_register(obj_index)?;
                    self.object_store.set_register_value(dst_reg, obj_index)?
                },
                Instruction::RegMod(dst_reg, src1_reg, src2_reg) => {
                    // 实现寄存器取模操作
                    let val1 = self.get_register_value(src1_reg)?;
                    let val2 = self.get_register_value(src2_reg)?;
                    
                    let result = match (val1, val2) {
                        (Value::Integer(a), Value::Integer(b)) => {
                            if *b == 0 {
                                return Err(PipitError::DivisionByZeroError("Division by zero in mod operation".to_string()));
                            }
                            Value::Integer(*a % *b)
                        },
                        (Value::Float(a), Value::Float(b)) => {
                            if *b == 0.0 {
                                return Err(PipitError::DivisionByZeroError("Division by zero in mod operation".to_string()));
                            }
                            Value::Float(*a % *b)
                        },
                        (Value::Integer(a), Value::Float(b)) => {
                            if *b == 0.0 {
                                return Err(PipitError::DivisionByZeroError("Division by zero in mod operation".to_string()));
                            }
                            Value::Float(*a as f64 % *b)
                        },
                        (Value::Float(a), Value::Integer(b)) => {
                            if *b == 0 {
                                return Err(PipitError::DivisionByZeroError("Division by zero in mod operation".to_string()));
                            }
                            Value::Float(*a % (*b as f64))
                        },
                        _ => return Err(PipitError::TypeError("Cannot perform mod operation on non-numeric values".to_string())),
                    };
                    
                    // 创建结果对象并存储到目标寄存器 - 使用惰性数据内存池优化
                    let obj_index = self.allocate_optimized_object(result)?;
                    self.object_store.assign_register(obj_index)?;
                    self.object_store.set_register_value(dst_reg, obj_index)?
                },
                Instruction::RegPow(dst_reg, src1_reg, src2_reg) => {
                    // 实现寄存器求幂操作
                    let val1 = self.get_register_value(src1_reg)?;
                    let val2 = self.get_register_value(src2_reg)?;
                    
                    let result = match (val1, val2) {
                        (Value::Integer(a), Value::Integer(b)) => {
                            // 处理特殊情况
                            if *a == 0 && *b == 0 {
                                return Err(PipitError::RuntimeError("0^0 is undefined".to_string()));
                            }
                            
                            // 检查是否可能溢出
                            let exp = match (*b).try_into() {
                                Ok(exp_val) => exp_val,
                                Err(_) => return Err(PipitError::RuntimeError("Exponent too large".to_string()))
                            };
                            let result_val = a.pow(exp);
                            Value::Integer(result_val)
                        },
                        (Value::Float(a), Value::Float(b)) => {
                            // 处理特殊情况
                            if *a == 0.0 && *b == 0.0 {
                                return Err(PipitError::RuntimeError("0.0^0.0 is undefined".to_string()));
                            }
                            Value::Float(a.powf(*b))
                        },
                        (Value::Integer(a), Value::Float(b)) => {
                            // 处理特殊情况
                            if *a == 0 && *b == 0.0 {
                                return Err(PipitError::RuntimeError("0^0.0 is undefined".to_string()));
                            }
                            Value::Float((*a as f64).powf(*b))
                        },
                        (Value::Float(a), Value::Integer(b)) => {
                            // 处理特殊情况
                            if *a == 0.0 && *b == 0 {
                                return Err(PipitError::RuntimeError("0.0^0 is undefined".to_string()));
                            }
                            
                            // 整数指数的特殊处理，提高效率
                            Value::Float(a.powi(*b))
                        },
                        _ => return Err(PipitError::TypeError("Cannot perform pow operation on non-numeric values".to_string())),
                    };
                    
                    // 创建结果对象并存储到目标寄存器 - 使用惰性数据内存池优化
                    let obj_index = self.allocate_optimized_object(result)?;
                    self.object_store.assign_register(obj_index)?;
                    self.object_store.set_register_value(dst_reg, obj_index)?
                },
                Instruction::RegPrint(_reg_index) => {
                    // 移除寄存器打印功能
                },
                Instruction::StackToRegister(stack_index, reg_index) => {
                    // 将栈中指定索引的值存入指定的寄存器中
                    self.stack_to_register(stack_index, reg_index)?;
                },
                Instruction::RegisterToStack(reg_index) => {
                    // 将寄存器中的值压入栈中
                    self.register_to_stack(reg_index)?;
                },
                // 循环优化专用指令
                Instruction::LoopInit(reg_index, value) => {
                    // 初始化循环计数器 - 使用惰性数据内存池优化
                    let obj_index = self.allocate_optimized_object(value.clone())?;
                    self.object_store.assign_register(obj_index)?;
                    self.object_store.set_register_value(reg_index, obj_index)?;
                },
                Instruction::LoopInc(reg_index) => {
                    // 循环自增 - 优化版本：直接在原地操作，避免创建新对象和引用计数操作
                    let reg_index_usize = reg_index as usize;
                    if reg_index_usize < self.object_store.register_map.len() {
                        if let Some(&obj_index) = self.object_store.register_map[reg_index_usize].as_ref() {
                            if let Some(obj) = self.object_store.objects.get_mut(obj_index) {
                                if let Value::Integer(ref mut i) = obj.value {
                                    // 直接在原地增加计数值，避免创建新对象
                                    *i += 1;
                                    // 更新访问计数，用于热点分析
                                    obj.access_count += 1;
                                }
                            }
                        }
                    }
                },
                Instruction::LoopDec(reg_index) => {
                    // 循环自减
                    if (reg_index as usize) < self.object_store.register_map.len() {
                        if let Some(&obj_index) = self.object_store.register_map[reg_index as usize].as_ref() {
                            let value = self.object_store.get_object_value(obj_index)?;
                            if let Value::Integer(i) = value {
                                let new_value = Value::Integer(i - 1);
                                // 使用惰性数据内存池优化
                                let new_obj_index = self.allocate_optimized_object(new_value)?;
                                self.object_store.assign_register(new_obj_index)?;
                                self.object_store.set_register_value(reg_index, new_obj_index)?;
                                
                                // 减少旧对象引用
                                self.object_store.decrement_ref_count(obj_index)?;
                            }
                        }
                    }
                },
                Instruction::LoopCheck(reg_index, limit_value, target) => {
                    // 检查循环条件 - 优化版本：减少边界检查次数，加速值的获取和比较
                    let reg_index_usize = reg_index as usize;
                    if reg_index_usize < self.object_store.register_map.len() {
                        if let Some(&obj_index) = self.object_store.register_map[reg_index_usize].as_ref() {
                            // 直接访问对象，避免通过get_object_value的额外开销
                            if let Some(obj) = self.object_store.objects.get(obj_index) {
                                if let Value::Integer(counter) = obj.value {
                                    if let Value::Integer(limit) = limit_value {
                                        // 直接进行整数比较，避免额外的解引用
                                        if counter >= limit {
                                            // 计数器达到或超过上限，跳出循环
                                            self.pc = target;
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                Instruction::LoopEnd => {
                    // 循环结束，这里可以添加一些统计或清理工作
                },
                // 跳转指令
                Instruction::Jump(target) => {
                    // 无条件跳转到指定位置
                    self.pc = target;
                },
                Instruction::JumpIfFalse(target) => {
                    // 如果栈顶值为假，则跳转到指定位置
                    if let Some(value) = self.pop_stack() {
                        let is_false = match value {
                            Value::Boolean(b) => !b,
                            Value::Integer(i) => i == 0,
                            Value::Float(f) => f == 0.0,
                            Value::String(s) => s.is_empty(),
                            Value::Array(arr) => arr.is_empty(),
                            _ => false,
                        };
                        
                        if is_false {
                            self.pc = target;
                        }
                    }
                },
                Instruction::JumpIfTrue(target) => {
                    // 如果栈顶值为真，则跳转到指定位置
                    if let Some(value) = self.pop_stack() {
                        let is_true = match value {
                            Value::Boolean(b) => b,
                            Value::Integer(i) => i != 0,
                            Value::Float(f) => f != 0.0,
                            Value::String(s) => !s.is_empty(),
                            Value::Array(arr) => !arr.is_empty(),
                            _ => true,
                        };
                        
                        if is_true {
                            self.pc = target;
                        }
                    }
                },
                // 计时器相关指令
                Instruction::TimerStart => {
                    // 启动计时器（简化实现，实际可能需要更复杂的时间管理）
                    let timestamp = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap()
                        .as_nanos() as i64;
                    let timer_value = Value::Integer(timestamp as i32);
                    // 使用惰性数据内存池优化
                    let obj_index = self.allocate_optimized_object(timer_value)?;
                    self.object_store.assign_register(obj_index)?;
                    self.object_store.set_register_value(self.object_store.get_timer_register(), obj_index)?;
                },
                Instruction::TimerStop => {
                    // 停止计时器
                    // 这里可以计算时间差并存储结果
                },
                Instruction::TimerRead(reg_index) => {
                    // 读取计时器值到寄存器
                    let timer_reg = self.object_store.get_timer_register();
                    if (timer_reg as usize) < self.object_store.register_map.len() {
                        if let Some(&obj_index) = self.object_store.register_map[timer_reg as usize].as_ref() {
                            self.object_store.increment_ref_count(obj_index)?;
                            self.object_store.set_register_value(reg_index, obj_index)?;
                        }
                    }
                },
                // 指针操作指令
                Instruction::PtrLoad(dst_reg, src_reg) => {
                    // 从指针位置加载值（简化实现）
                    if (src_reg as usize) < self.object_store.register_map.len() {
                        if let Some(&obj_index) = self.object_store.register_map[src_reg as usize].as_ref() {
                            // 这里应该实现实际的指针解引用逻辑
                            // 当前实现只是简单复制引用
                            self.object_store.increment_ref_count(obj_index)?;
                            self.object_store.set_register_value(dst_reg, obj_index)?;
                        }
                    }
                },
                Instruction::PtrStore(dst_reg, src_reg) => {
                    // 存储值到指针位置（简化实现）
                    if (src_reg as usize) < self.object_store.register_map.len() {
                        if let Some(&obj_index) = self.object_store.register_map[src_reg as usize].as_ref() {
                            // 这里应该实现实际的指针存储逻辑
                            // 当前实现只是简单复制引用
                            self.object_store.increment_ref_count(obj_index)?;
                            self.object_store.set_register_value(dst_reg, obj_index)?;
                        }
                    }
                },
                Instruction::PtrAdd(reg_index, value) => {
                    // 指针加法
                    if (reg_index as usize) < self.object_store.register_map.len() {
                        if let Some(&obj_index) = self.object_store.register_map[reg_index as usize].as_ref() {
                            let reg_value = self.object_store.get_object_value(obj_index)?;
                            if let (Value::Integer(ptr_val), Value::Integer(offset)) = (reg_value, value) {
                                let new_value = Value::Integer(ptr_val + offset);
                                // 使用惰性数据内存池优化
                                let new_obj_index = self.allocate_optimized_object(new_value)?;
                                self.object_store.assign_register(new_obj_index)?;
                                self.object_store.set_register_value(reg_index, new_obj_index)?;
                                
                                // 减少旧对象引用
                                self.object_store.decrement_ref_count(obj_index)?;
                            }
                        }
                    }
                },
                Instruction::PtrSub(reg_index, value) => {
                    // 指针减法
                    if (reg_index as usize) < self.object_store.register_map.len() {
                        if let Some(&obj_index) = self.object_store.register_map[reg_index as usize].as_ref() {
                            let reg_value = self.object_store.get_object_value(obj_index)?;
                            if let (Value::Integer(ptr_val), Value::Integer(offset)) = (reg_value, value) {
                                let new_value = Value::Integer(ptr_val - offset);
                                // 使用惰性数据内存池优化
                                let new_obj_index = self.allocate_optimized_object(new_value)?;
                                self.object_store.assign_register(new_obj_index)?;
                                self.object_store.set_register_value(reg_index, new_obj_index)?;
                                
                                // 减少旧对象引用
                                self.object_store.decrement_ref_count(obj_index)?;
                            }
                        }
                    }
                },
                // 专用指针操作指令
                Instruction::LoopPtrLoad(dst_reg, loop_level) => {
                    // 从循环指针加载值
                    if let Ok(ptr_reg) = self.object_store.get_loop_counter_pointer(loop_level as usize) {
                        if (ptr_reg as usize) < self.object_store.register_map.len() {
                            if let Some(&obj_index) = self.object_store.register_map[ptr_reg as usize].as_ref() {
                                self.object_store.increment_ref_count(obj_index)?;
                                self.object_store.set_register_value(dst_reg, obj_index)?;
                            }
                        }
                    }
                },
                Instruction::LoopPtrStore(loop_level, src_reg) => {
                    // 存储值到循环指针
                    if let Ok(ptr_reg) = self.object_store.get_loop_counter_pointer(loop_level as usize) {
                        if (src_reg as usize) < self.object_store.register_map.len() {
                            if let Some(&obj_index) = self.object_store.register_map[src_reg as usize].as_ref() {
                                self.object_store.increment_ref_count(obj_index)?;
                                self.object_store.set_register_value(ptr_reg, obj_index)?;
                            }
                        }
                    }
                },
                Instruction::TimerPtrLoad(dst_reg) => {
                    // 从计时器指针加载值
                    let ptr_reg = self.object_store.get_timer_pointer();
                    if (ptr_reg as usize) < self.object_store.register_map.len() {
                        if let Some(&obj_index) = self.object_store.register_map[ptr_reg as usize].as_ref() {
                            self.object_store.increment_ref_count(obj_index)?;
                            self.object_store.set_register_value(dst_reg, obj_index)?;
                        }
                    }
                },
                Instruction::TimerPtrStore(src_reg) => {
                    // 存储值到计时器指针
                    let ptr_reg = self.object_store.get_timer_pointer();
                    if (src_reg as usize) < self.object_store.register_map.len() {
                        if let Some(&obj_index) = self.object_store.register_map[src_reg as usize].as_ref() {
                            self.object_store.increment_ref_count(obj_index)?;
                            self.object_store.set_register_value(ptr_reg, obj_index)?;
                        }
                    }
                },
                Instruction::GeneralPtrLoad(dst_reg, ptr_index) => {
                    // 从通用指针加载值
                    if let Ok(ptr_reg) = self.object_store.get_general_purpose_pointer(ptr_index as usize) {
                        if (ptr_reg as usize) < self.object_store.register_map.len() {
                            if let Some(&obj_index) = self.object_store.register_map[ptr_reg as usize].as_ref() {
                                self.object_store.increment_ref_count(obj_index)?;
                                self.object_store.set_register_value(dst_reg, obj_index)?;
                            }
                        }
                    }
                },
                Instruction::GeneralPtrStore(ptr_index, src_reg) => {
                    // 存储值到通用指针
                    if let Ok(ptr_reg) = self.object_store.get_general_purpose_pointer(ptr_index as usize) {
                        if (src_reg as usize) < self.object_store.register_map.len() {
                            if let Some(&obj_index) = self.object_store.register_map[src_reg as usize].as_ref() {
                                self.object_store.increment_ref_count(obj_index)?;
                                self.object_store.set_register_value(ptr_reg, obj_index)?;
                            }
                        }
                    }
                },
                // 缓存相关指令
                Instruction::CachePush(value) => {
                    // 将值推入缓存
                    self.cache_pool.cache_value(value.clone())?;
                },
                Instruction::CachePop(reg_index) => {
                    // 从缓存弹出值到寄存器
                    if let Some(value) = self.stack.pop() {
                        // 使用惰性数据内存池优化
                        let obj_index = self.allocate_optimized_object(value)?;
                        self.object_store.assign_register(obj_index)?;
                        self.object_store.set_register_value(reg_index, obj_index)?;
                    }
                },
                Instruction::CacheStore(_index) => {
                    // 将栈顶值存储到缓存池指定位置
                    if let Some(value) = self.stack.pop() {
                        // 注意：这里简化处理，实际应该支持在指定位置存储
                        self.cache_pool.cache_value(value)?;
                    }
                },
                Instruction::CacheLoad(index, reg_index) => {
                    // 从缓存池加载值到寄存器
                    if let Some(cached_value) = self.cache_pool.get_cached_value(index) {
                        if let Value::CachedValue(value) = cached_value {
                            // 使用惰性数据内存池优化
                            let obj_index = self.allocate_optimized_object(*value.clone())?;
                            self.object_store.assign_register(obj_index)?;
                            self.object_store.set_register_value(reg_index, obj_index)?
                        }
                    }
                },
                Instruction::CollectorCombine => {
                    // 组合收集器（简化实现）
                    // 这里可以实现将多个收集器组合的逻辑
                },
                Instruction::CollectorClear => {
                    // 清空收集器
                    self.handle_collector.clear();
                    self.stack_frame_collector.clear();
                    self.cache_pool.clear();
                },
                // 内联缓存相关指令
                Instruction::ICCreate(entry_index) => {
                    // 创建内联缓存
                    let cache_id = self.inline_cache_manager.create_cache();
                    // 将cache_id存储到指定位置，这里简化处理，存储到变量中
                    self.variables.insert(entry_index, Value::Integer(cache_id as i32));
                },
                Instruction::ICUpdate(cache_id, class_id, method_id, call_target) => {
                    // 更新内联缓存
                    self.inline_cache_manager.update_cache(cache_id as usize, class_id as usize, method_id as usize, call_target as usize)?;
                },
                Instruction::ICLookup(cache_id, class_id, result_reg) => {
                    // 查找内联缓存
                    if let Ok(Some((method_id, call_target))) = self.inline_cache_manager.lookup(cache_id as usize, class_id as usize) {
                        // 创建结果对象并存储到结果寄存器
                        let result_value = Value::Array(vec![Value::Integer(method_id as i32), Value::Integer(call_target as i32)]);
                        // 使用惰性数据内存池优化
                        let obj_index = self.allocate_optimized_object(result_value)?;
                        self.object_store.assign_register(obj_index)?;
                        self.object_store.set_register_value(result_reg, obj_index)?
                    }
                },
                Instruction::ICGetMethod(cache_id, class_id, result_reg) => {
                    // 获取方法地址
                    if let Ok(Some((method_id, _))) = self.inline_cache_manager.lookup(cache_id as usize, class_id as usize) {
                        // 将方法ID存储到结果寄存器
                        // 使用惰性数据内存池优化
                        let obj_index = self.allocate_optimized_object(Value::Integer(method_id as i32))?;
                        self.object_store.assign_register(obj_index)?;
                        self.object_store.set_register_value(result_reg, obj_index)?;
                    }
                },
                // 原生函数调用指令
                Instruction::NativeCall(func_name) => {
                    // 在native_functions中查找对应的函数
                    if let Some(native_func) = self.native_functions.get(&func_name) {
                        // 调用原生函数
                        native_func(self);
                    } else {
                        // 如果找不到函数，返回错误
                        return Err(PipitError::RuntimeError(format!("Native function not found: {}", func_name)));
                    }
                },
                Instruction::MakeArray(size) => {
                    // 创建包含n个元素的数组
                    if size > self.stack.len() {
                        return Err(PipitError::RuntimeError(format!("Not enough elements on stack for array of size {}", size)));
                    }
                    
                    let mut elements = Vec::with_capacity(size);
                    for _ in 0..size {
                        if let Some(value) = self.pop_stack() {
                            elements.insert(0, value); // 逆序插入，保持正确顺序
                        }
                    }
                    
                    self.push_stack(Value::Array(elements))?;
                },
                Instruction::ArrayGet => {
                    // 获取数组元素 arr[index]
                    if self.stack_len() < 2 {
                        return Err(PipitError::RuntimeError("Stack underflow in array get operation".to_string()));
                    }
                    
                    let index = self.pop_stack().unwrap();
                    let array = self.pop_stack().unwrap();
                    
                    match (array, index) {
                        (Value::Array(arr), Value::Integer(idx)) => {
                            let idx = idx as usize;
                            if idx < arr.len() {
                                self.push_stack(arr[idx].clone())?;
                            } else {
                                return Err(PipitError::RuntimeError(format!("Array index {} out of bounds for array of length {}", idx, arr.len())));
                            }
                        },
                        _ => {
                            return Err(PipitError::TypeError("Array get operation requires array and integer index".to_string()));
                        }
                    }
                },
                Instruction::ArraySet => {
                    // 设置数组元素 arr[index] = value
                    if self.stack_len() < 3 {
                        return Err(PipitError::RuntimeError("Stack underflow in array set operation".to_string()));
                    }
                    
                    let value = self.pop_stack().unwrap();
                    let index = self.pop_stack().unwrap();
                    let array = self.pop_stack().unwrap();
                    
                    match (array, index) {
                        (Value::Array(mut arr), Value::Integer(idx)) => {
                            let idx = idx as usize;
                            if idx < arr.len() {
                                arr[idx] = value;
                                self.push_stack(Value::Array(arr))?;
                            } else {
                                return Err(PipitError::RuntimeError(format!("Array index {} out of bounds for array of length {}", idx, arr.len())));
                            }
                        },
                        _ => {
                            return Err(PipitError::TypeError("Array set operation requires array, integer index, and value".to_string()));
                        }
                    }
                },
                Instruction::ArrayLength => {
                    // 获取数组长度
                    if self.stack_len() < 1 {
                        return Err(PipitError::RuntimeError("Stack underflow in array length operation".to_string()));
                    }
                    
                    let array = self.pop_stack().unwrap();
                    
                    match array {
                        Value::Array(arr) => {
                            self.push_stack(Value::Integer(arr.len() as i32))?;
                        },
                        _ => {
                            return Err(PipitError::TypeError("Array length operation requires array".to_string()));
                        }
                    }
                },
                Instruction::MakeStruct(field_count) => {
                    // 创建结构体实例
                    if field_count > self.stack.len() {
                        return Err(PipitError::RuntimeError(format!("Not enough elements on stack for struct with {} fields", field_count)));
                    }
                    
                    let mut fields = HashMap::new();
                    for i in 0..field_count {
                        if let Some(value) = self.pop_stack() {
                            fields.insert(format!("field_{}", field_count - 1 - i), value);
                        }
                    }
                    
                    self.push_stack(Value::Struct(fields))?
                },
                Instruction::StructGet(field_name) => {
                    // 获取结构体字段值或特殊属性
                    if self.stack_len() < 1 {
                        return Err(PipitError::RuntimeError("Stack underflow in struct get operation".to_string()));
                    }
                    
                    let struct_value = self.pop_stack().unwrap();
                    
                    // 特殊处理数组的length属性
                    if field_name == "length" {
                        if let Value::Array(arr) = struct_value {
                            self.push_stack(Value::Integer(arr.len() as i32))?;
                            continue;
                        }
                    }
                    
                    match struct_value {
                        Value::Struct(fields) => {
                            if let Some(value) = fields.get(&field_name) {
                                self.push_stack(value.clone())?
                            } else {
                                return Err(PipitError::RuntimeError(format!("Field '{}' not found in struct", field_name)));
                            }
                        },
                        _ => {
                            return Err(PipitError::TypeError("Struct get operation requires struct value".to_string()));
                        }
                    }
                },
                Instruction::StructSet(field_name) => {
                    // 设置结构体字段值
                    if self.stack_len() < 2 {
                        return Err(PipitError::RuntimeError("Stack underflow in struct set operation".to_string()));
                    }
                    
                    let value = self.pop_stack().unwrap();
                    let struct_value = self.pop_stack().unwrap();
                    
                    match struct_value {
                        Value::Struct(mut fields) => {
                            fields.insert(field_name, value);
                            self.push_stack(Value::Struct(fields))?
                        },
                        _ => {
                            return Err(PipitError::TypeError("Struct set operation requires struct value".to_string()));
                        }
                    }
                },
                Instruction::MakeClass(class_id, arg_count) => {
                    // 创建类实例
                    if arg_count > self.stack.len() {
                        return Err(PipitError::RuntimeError(format!("Not enough arguments on stack for class instantiation (expected {})", arg_count)));
                    }
                    
                    let mut args = Vec::with_capacity(arg_count);
                    for _ in 0..arg_count {
                        if let Some(arg) = self.pop_stack() {
                            args.insert(0, arg); // 逆序插入，保持正确顺序
                        }
                    }
                    
                    // 查找类定义
                    let class_def = self.classes.get(class_id.to_string().as_str())
                        .ok_or_else(|| PipitError::RuntimeError(format!("Class with id {} not found", class_id)))?;
                    
                    // 创建类实例
                    let instance = ClassInstance {
                        class_def: class_def.clone(),
                        fields: HashMap::new(),
                    };
                    
                    self.push_stack(Value::Instance(Box::new(instance)))?
                },
                Instruction::CallMethod(method_name, arg_count) => {
                    // 调用对象方法
                    if arg_count + 1 > self.stack.len() {
                        return Err(PipitError::RuntimeError(format!("Not enough arguments on stack for method call (expected {})", arg_count + 1)));
                    }
                    
                    let mut args = Vec::with_capacity(arg_count);
                    for _ in 0..arg_count {
                        if let Some(arg) = self.pop_stack() {
                            args.insert(0, arg);
                        }
                    }
                    
                    let object = self.pop_stack().unwrap();
                    
                    match object {
                        Value::Instance(instance) => {
                            // 查找方法
                            if let Some((method_start, param_count)) = instance.class_def.methods.get(&method_name) {
                                if args.len() != *param_count {
                                    return Err(PipitError::RuntimeError(format!("Method {} expects {} arguments, got {}", method_name, param_count, args.len())));
                                }
                                
                                // 保存当前执行状态
                                let saved_pc = self.pc;
                                let saved_variables = self.variables.clone();
                                
                                // 设置方法参数
                                self.variables.clear();
                                for (i, arg) in args.iter().enumerate() {
                                    self.variables.insert(i, arg.clone());
                                }
                                
                                // 设置this引用 - 克隆实例避免借用问题
                                self.variables.insert(999, Value::Instance(instance.clone())); // 特殊索引用于this
                                
                                // 跳转到方法
                                self.pc = *method_start;
                                
                                // 执行方法
                                self.execute()?;
                                
                                // 恢复执行状态
                                self.pc = saved_pc;
                                self.variables = saved_variables;
                            } else {
                                return Err(PipitError::RuntimeError(format!("Method '{}' not found", method_name)));
                            }
                        },
                        _ => {
                            return Err(PipitError::TypeError("Method call requires instance".to_string()));
                        }
                    }
                },
                // 其他指令可以继续添加
                // 错误处理相关指令
                Instruction::TryBegin(catch_pos) => {
                    // 保存当前程序计数器位置，用于try块结束后的跳转
                    self.try_stack.push(self.pc);
                    // 保存catch块的位置
                    self.catch_stack.push(catch_pos);
                    // 初始化finally块的位置为None
                    self.finally_stack.push(None);
                },
                Instruction::TryEnd => {
                    // 弹出try块相关的状态
                    if !self.try_stack.is_empty() {
                        self.try_stack.pop();
                    }
                    if !self.catch_stack.is_empty() {
                        self.catch_stack.pop();
                    }
                    if !self.finally_stack.is_empty() {
                        self.finally_stack.pop();
                    }
                },
                Instruction::CatchBegin(finally_pos) => {
                    // 保存finally块的位置（如果有）
                    if let Some(last) = self.finally_stack.last_mut() {
                        *last = if finally_pos > 0 { Some(finally_pos) } else { None };
                    }
                    // 标记当前位置为catch块开始
                    self.current_catch_pos = Some(self.pc - 1);
                },
                Instruction::CatchEnd => {
                    // 重置当前catch块位置
                    self.current_catch_pos = None;
                },
                Instruction::FinallyBegin(after_pos) => {
                    // 保存finally块后的位置
                    self.finally_after_stack.push(after_pos);
                },
                Instruction::FinallyEnd => {
                    // 弹出finally块后的位置
                    if !self.finally_after_stack.is_empty() {
                        self.finally_after_stack.pop();
                    }
                },
                Instruction::Throw => {
                    // 获取要抛出的值
                    if let Some(thrown_value) = self.pop_stack() {
                        // 处理异常：找到最近的catch块或finally块
                        if !self.catch_stack.is_empty() {
                            let catch_pos = *self.catch_stack.last().unwrap();
                            // 保存抛出的值到特殊变量
                            self.variables.insert(998, thrown_value); // 特殊索引用于异常值
                            // 跳转到catch块
                            self.pc = catch_pos;
                        } else {
                            // 没有catch块，输出错误信息并终止程序
                            eprintln!("Unhandled exception: {:?}", thrown_value);
                            break;
                        }
                    }
                },
                Instruction::CreateError(message) => {
                    // 创建错误对象并压入栈
                    let error_obj = Value::Struct(HashMap::from([
                        ("message".to_string(), Value::String(message.clone())),
                        ("type".to_string(), Value::String("Error".to_string()))
                    ]));
                    self.push_stack(error_obj)?;
                },
                // 模块系统相关指令
                Instruction::LoadModule(module_path) => {
                    // 加载模块
                    // 尝试加载用户定义的模块文件
                    if module_path.ends_with(".pi") {
                        // 获取完整的模块文件路径
                        let full_path = std::path::Path::new(&module_path);
                        if full_path.exists() {
                            // 读取模块内容
                            if let Ok(_content) = std::fs::read_to_string(full_path) {
                                // 模拟加载模块，实际应该编译并执行模块代码
                                eprintln!("Loading module file: {}", module_path);
                                self.push_stack(Value::Boolean(true))?;
                                return Ok(());
                            } else {
                                eprintln!("Failed to read module file: {}", module_path);
                            }
                        } else {
                            eprintln!("Module file not found: {}", module_path);
                        }
                    }
                    
                    // 尝试加载预定义的系统模块
                    let module = match module_path.as_str() {
                        "core" => Module::Core,
                        "io" => Module::IO,
                        "math" => Module::Math,
                        "string" => Module::String,
                        "os" => Module::OS,
                        "concurrent" => Module::Concurrent,
                        "syscall" => Module::Syscall,
                        _ => {
                            eprintln!("Unknown module: {}", module_path);
                            // 创建并压入错误对象
                            let error_obj = Value::Struct(HashMap::from([
                                ("message".to_string(), Value::String(format!("Unknown module: '{}'", module_path))),
                                ("type".to_string(), Value::String("ModuleError".to_string()))
                            ]));
                            self.push_stack(error_obj)?;
                            return Ok(());
                        }
                    };
                    
                    if let Err(err) = self.load_module(module) {
                        eprintln!("Failed to load module '{}': {:?}", module_path, err);
                        // 创建并压入错误对象
                        let error_obj = Value::Struct(HashMap::from([
                            ("message".to_string(), Value::String(format!("Failed to load module '{}'", module_path))),
                            ("type".to_string(), Value::String("ModuleError".to_string()))
                        ]));
                        self.push_stack(error_obj)?;
                    } else {
                        // 压入成功标志
                        self.push_stack(Value::Boolean(true))?;
                    }
                },
                Instruction::ImportSymbol(import_name, alias) => {
                    // 导入符号
                    // 查找导入的符号
                    // 这里我们使用一个简单的模拟实现
                    eprintln!("Importing symbol: {} as {}", import_name, alias);
                    
                    // 检查导入的名称是否是标准库函数
                    if crate::stdlib_registry::is_stdlib_function(&import_name) {
                        // 如果是标准库函数，创建NativeFunction类型的对象
                        let native_func = Value::NativeFunction(import_name.clone());
                        let var_index = self.variables.len();
                        self.variables.insert(var_index, native_func);
                        
                        // 同时在module_registry中记录这个导入
                        self.module_registry.add_import(alias.clone(), import_name.clone());
                    } else {
                        // 尝试从其他已加载的模块中导入符号
                        if let Some(exported_value) = self.module_registry.get_exported_value(&import_name) {
                            // 如果找到已导出的值，直接使用
                            let var_index = self.variables.len();
                            self.variables.insert(var_index, exported_value.clone());
                            self.module_registry.add_import(alias.clone(), import_name.clone());
                        } else {
                            // 对于其他符号，创建一个占位符
                            let placeholder = Value::String(import_name.clone());
                            let var_index = self.variables.len();
                            self.variables.insert(var_index, placeholder);
                            
                            eprintln!("Warning: Imported symbol '{}' not found in standard library or any loaded module", import_name);
                        }
                    }
                },
                Instruction::ExportSymbol(symbol_name, alias) => {
                    // 导出符号
                    eprintln!("Exporting symbol: {} as {}", symbol_name, alias);
                    
                    // 将符号添加到当前模块的导出表中
                    self.module_registry.add_export(alias.clone(), symbol_name.clone());
                    
                    // 存储导出的符号，以便其他模块可以导入
                    if let Some(value) = self.variables.get(&self.variables.len()) {
                        self.module_registry.store_exported_value(alias, value.clone());
                    }
                },
                Instruction::Call(function_index) => {
                    // 调用函数
                    
                    // 首先检测是否是尾递归调用，这是优化的核心
                    let is_tail_call = self.detect_tail_call(function_index, current_pc);
                    
                    // 首先尝试直接使用function_index作为函数地址
                    if let Some(&arg_count) = self.functions.get(&function_index) {
                        
                        // 确保栈上有足够的参数
                        if arg_count > self.stack.len() {
                            return Err(PipitError::RuntimeError(format!("Not enough arguments for function call (expected {})", arg_count)));
                        }
                        
                        // 从栈中弹出参数
                        let mut args = Vec::with_capacity(arg_count);
                        for _ in 0..arg_count {
                            if let Some(arg) = self.pop_stack() {
                                args.insert(0, arg);
                            }
                        }
                        
                        // 保存当前执行状态
                        let return_address = current_pc + 1; // 使用保存的当前pc，+1是因为我们已经增加了pc
                        
                        if is_tail_call && !self.call_stack.is_empty() {
                            // 尾递归优化：重用当前调用帧而不是创建新的
                            // 1. 找到当前调用帧
                            let current_frame = self.call_stack.last_mut().unwrap();
                            
                            // 2. 更新调用帧中的参数
                            for (i, arg) in args.iter().enumerate() {
                                let param_index = -(i as i32 + 1); // -1, -2, -3, ...
                                current_frame.set_local(param_index, arg.clone());
                            }
                            
                            // 3. 直接跳转到函数，而不创建新的调用帧
                            self.pc = function_index;
                            
                            // 记录尾递归优化的使用情况
                            self.inline_cache_manager.record_tail_call_optimization(function_index);
                        } else {
                            // 常规函数调用：创建新的调用帧
                                let mut new_frame = CallFrame::new(return_address, function_index, arg_count, 16, 256);
                                
                                // 设置函数参数到调用帧的局部变量中（使用负索引，从-1开始）
                                for (i, arg) in args.iter().enumerate() {
                                    let param_index = -(i as i32 + 1); // -1, -2, -3, ...
                                    new_frame.set_local(param_index, arg.clone());
                                }
                                
                                // 调用栈支持动态增长，无需硬限制
                                // 预分配策略：当接近容量时自动扩展
                                if self.call_stack.len() >= self.call_stack.capacity() {
                                    let new_capacity = std::cmp::max(self.call_stack.capacity() * 2, 1024);
                                    self.call_stack.reserve(new_capacity - self.call_stack.capacity());
                                }
                                
                                // 将新的调用帧压入调用栈
                                self.call_stack.push(new_frame);
                                
                                // 设置pc到函数地址 - 注意：不增加pc，因为我们想直接跳转到函数
                                self.pc = function_index;
                        }
                        
                        // 注意：不在这里执行函数，而是让主循环继续执行，这样Return指令才能正确处理
                    } else if let Some(var_value) = self.variables.get(&function_index).cloned() {
                        // 如果直接查找失败，再尝试在变量中查找函数
                        match var_value {
                            Value::NativeFunction(func_name) => {
                                // 调用原生函数
                                if let Some(native_func) = self.native_functions.get(&func_name) {
                                    native_func(self);
                                } else {
                                    return Err(PipitError::RuntimeError(format!("Native function not found: {}", func_name)));
                                }
                            },
                            Value::Function(func_addr) => {
                                // 克隆func_addr以避免借用问题
                                let cloned_func_addr = func_addr;
                                // 获取函数参数数量
                                let arg_count = self.functions.get(&cloned_func_addr).copied().unwrap_or(0);
                                
                                // 确保栈上有足够的参数
                                if arg_count > self.stack.len() {
                                    return Err(PipitError::RuntimeError(format!("Not enough arguments for function call (expected {})", arg_count)));
                                }
                                
                                // 从栈中弹出参数
                                let mut args = Vec::with_capacity(arg_count);
                                for _ in 0..arg_count {
                                    if let Some(arg) = self.pop_stack() {
                                        args.insert(0, arg);
                                    }
                                }
                                
                                // 保存当前执行状态
                                let return_address = current_pc + 1; // 使用保存的当前pc，+1是因为我们已经增加了pc
                                
                                if is_tail_call && !self.call_stack.is_empty() {
                                    // 尾递归优化：重用当前调用帧而不是创建新的
                                    // 1. 找到当前调用帧
                                    let current_frame = self.call_stack.last_mut().unwrap();
                                    
                                    // 2. 更新调用帧中的参数
                                    for (i, arg) in args.iter().enumerate() {
                                        let param_index = -(i as i32 + 1); // -1, -2, -3, ...
                                        current_frame.set_local(param_index, arg.clone());
                                    }
                                    
                                    // 3. 直接跳转到函数，而不创建新的调用帧
                                    self.pc = cloned_func_addr;
                                    
                                    // 记录尾递归优化的使用情况
                                    self.inline_cache_manager.record_tail_call_optimization(cloned_func_addr);
                                } else {
                                    // 常规函数调用：创建新的调用帧
                                let mut new_frame = CallFrame::new(return_address, cloned_func_addr, arg_count, 16, 256);
                                
                                // 设置函数参数到调用帧的局部变量中（使用负索引，从-1开始）
                                for (i, arg) in args.iter().enumerate() {
                                    let param_index = -(i as i32 + 1); // -1, -2, -3, ...
                                    new_frame.set_local(param_index, arg.clone());
                                }
                                
                                // 调用栈支持动态增长，无需硬限制
                                // 预分配策略：当接近容量时自动扩展
                                if self.call_stack.len() >= self.call_stack.capacity() {
                                    let new_capacity = std::cmp::max(self.call_stack.capacity() * 2, 1024);
                                    self.call_stack.reserve(new_capacity - self.call_stack.capacity());
                                }
                                
                                // 将新的调用帧压入调用栈
                                self.call_stack.push(new_frame);
                                
                                // 设置pc到函数地址 - 注意：不增加pc，因为我们想直接跳转到函数
                                self.pc = cloned_func_addr;
                                }
                                
                                // 注意：不在这里执行函数，而是让主循环继续执行，这样Return指令才能正确处理
                            },
                            _ => {
                                return Err(PipitError::TypeError(format!("Cannot call non-function value at index {}", function_index)));
                            }
                        }
                    } else {
                        // 如果找不到函数，返回错误
                        return Err(PipitError::RuntimeError(format!("Function not found at index {}", function_index)));
                    }
                },
                _ => {
                    // 对于未实现的指令，返回错误
                    return Err(PipitError::NotImplementedError(
                        format!("Instruction not implemented: {:?}", instruction)
                    ));
                }
            }
        }
        
        // 启动并发垃圾回收（非阻塞）
        self.concurrent_gc.start_gc();
        
        // 执行全局优化
        // 将optimization_manager临时移出，避免可变借用冲突
        let mut optimization_manager = std::mem::replace(&mut self.optimization_manager, advanced_optimizations::OptimizationManager::new(advanced_optimizations::OptimizationLevel::None));
        let _ = optimization_manager.optimize_virtual_machine(self);
        self.optimization_manager = optimization_manager;
        
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    // 获取寄存器中的值（不可变引用）
    pub fn get_register_value(&self, reg_index: u8) -> Result<&Value> {
        if (reg_index as usize) < self.object_store.register_map.len() {
            if let Some(&obj_index) = self.object_store.register_map[reg_index as usize].as_ref() {
                // 修复借用冲突问题
                self.object_store.objects.get(obj_index)
                    .map(|obj| &obj.value)
                    .ok_or_else(|| PipitError::RuntimeError("Object not found".to_string()))
            } else {
                Err(PipitError::RuntimeError("Register is empty".to_string()))
            }
        } else {
            Err(PipitError::RuntimeError("Register index out of bounds".to_string()))
        }
    }


    
    // 打印值的辅助函数（带换行）
    fn print_value(&self, value: &Value) -> Result<()> {
        match value {
            Value::Integer(i) => println!("{}", i),
            Value::Float(f) => println!("{}", f),
            Value::Boolean(b) => println!("{}", b),
            Value::String(s) => println!("{}", s),
            Value::Array(arr) => {
                print!("[");
                let mut first = true;
                for elem in arr {
                    if !first {
                        print!(", ");
                    }
                    self.print_value_no_newline(elem)?;
                    first = false;
                }
                println!("]");
            },
            Value::Function(f) => println!("<function: {:#x}>", f),
            Value::NativeFunction(name) => println!("<native function: {name}>", name = name),
            _ => println!("{:?}", value),
        }
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }

    // 打印值的辅助函数（不带换行）
    fn print_value_no_newline(&self, value: &Value) -> Result<()> {
        match value {
            Value::Integer(i) => print!("{}", i),
            Value::Float(f) => print!("{}", f),
            Value::Boolean(b) => print!("{}", b),
            Value::String(s) => print!("{}", s),
            Value::Array(arr) => {
                print!("[");
                let mut first = true;
                for elem in arr {
                    if !first {
                        print!(", ");
                    }
                    self.print_value_no_newline(elem)?;
                    first = false;
                }
                print!("]");
            },
            Value::Function(f) => print!("<function: {:#x}>", f),
            Value::NativeFunction(name) => print!("<native function: {name}>", name = name),
            _ => print!("{:?}", value),
        }
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 获取栈长度
    pub fn stack_len(&self) -> usize {
        self.stack.len()
    }
    
    /// 从栈中弹出一个值
    pub fn pop_stack(&mut self) -> Option<Value> {
        self.stack.pop()
    }
    
    /// 向栈中压入一个值 - 支持动态栈增长和惰性数据内存池优化
    pub fn push_stack(&mut self, value: Value) -> Result<()> {
        // 动态栈增长策略：没有硬限制，但会记录增长情况
        // 预分配策略：当栈大小接近容量时自动扩展
        if self.stack.len() >= self.stack.capacity() {
            // 动态扩展容量，使用指数增长策略
            let new_capacity = std::cmp::max(self.stack.capacity() * 2, 1024);
            self.stack.reserve(new_capacity - self.stack.capacity());
            
            // 记录栈扩展事件
            self.inline_cache_manager.record_stack_expansion(self.stack.len());
        }
        
        // 存储值到栈中
        self.stack.push(value);
        
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
        io::stdout().flush()?;
        Ok(())
    }
    
    /// 执行加法指令
    pub fn execute_add(&mut self) -> Result<()> {
        
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in add operation".to_string()));
        }
        
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
        
        // 使用类型检查器进行类型转换
        let type_checker = TypeChecker::new(Arc::new(TypeEnvironment::new()));
        
        match (a, b) {
            // 相同数字类型的加法
            (Value::Integer(a), Value::Integer(b)) => {
                let _ = self.push_stack(Value::Integer(a + b));
                Ok(())
            },
            (Value::Float(a), Value::Float(b)) => {
                let _ = self.push_stack(Value::Float(a + b));
                Ok(())
            },
            // 不同数字类型的加法（自动转换）
            (Value::Integer(a), Value::Float(b)) => {
                let _ = self.push_stack(Value::Float(a as f64 + b));
                Ok(())
            },
            (Value::Float(a), Value::Integer(b)) => {
                let _ = self.push_stack(Value::Float(a + b as f64));
                Ok(())
            },
            // 字符串与字符串的加法
            (Value::String(a), Value::String(b)) => {
                let _ = self.push_stack(Value::String(format!("{}{}", a, b)));
                Ok(())
            },
            // 字符串与其他类型的加法（自动转换为字符串）
            (Value::String(a), b_val) => {
                match type_checker.try_coerce_value(b_val, &Type::String) {
                    Ok(Value::String(b)) => {
                        let _ = self.push_stack(Value::String(format!("{}{}", a, b)));
                        Ok(())
                    },
                    Ok(_) => Err(PipitError::TypeError("Failed to convert to string".to_string())),
                    Err(e) => Err(e)
                }
            },
            (a_val, Value::String(b)) => {
                match type_checker.try_coerce_value(a_val, &Type::String) {
                    Ok(Value::String(a)) => {
                        let _ = self.push_stack(Value::String(format!("{}{}", a, b)));
                        Ok(())
                    },
                    Ok(_) => Err(PipitError::TypeError("Failed to convert to string".to_string())),
                    Err(e) => Err(e)
                }
            },
            // 其他类型的加法，尝试转换为相同类型
            (a_val, b_val) => {
                // 尝试将b转换为a的类型
                let a_type = type_checker.infer_type_from_value(&a_val);
                match type_checker.try_coerce_value(b_val.clone(), &a_type) {
                    Ok(converted_b) => {
                        match (a_val, converted_b) {
                            (Value::Integer(a), Value::Integer(b)) => {
                                let _ = self.push_stack(Value::Integer(a + b));
                                Ok(())
                            },
                            (Value::Float(a), Value::Float(b)) => {
                                let _ = self.push_stack(Value::Float(a + b));
                                Ok(())
                            },
                            (Value::Boolean(a), Value::Boolean(b)) => {
                                // 布尔值加法作为逻辑或
                                let _ = self.push_stack(Value::Boolean(a || b));
                                Ok(())
                            },
                            _ => Err(PipitError::TypeError("Cannot add values of incompatible types".to_string()))
                        }
                    },
                    // 如果转换失败，尝试将a转换为b的类型
                    Err(_) => {
                        let b_type = type_checker.infer_type_from_value(&b_val);
                        match type_checker.try_coerce_value(a_val, &b_type) {
                            Ok(converted_a) => {
                                match (converted_a, b_val) {
                                    (Value::Integer(a), Value::Integer(b)) => {
                                        let _ = self.push_stack(Value::Integer(a + b));
                                        Ok(())
                                    },
                                    (Value::Float(a), Value::Float(b)) => {
                                        let _ = self.push_stack(Value::Float(a + b));
                                        Ok(())
                                    },
                                    (Value::Boolean(a), Value::Boolean(b)) => {
                                        let _ = self.push_stack(Value::Boolean(a || b));
                                        Ok(())
                                    },
                                    _ => Err(PipitError::TypeError("Cannot add values of incompatible types".to_string()))
                                }
                            },
                            // 两种转换都失败
                            Err(_) => Err(PipitError::TypeError("Cannot add values of different types".to_string()))
                        }
                    }
                }
            },
        }
    }
    
    /// 执行减法指令
    pub fn execute_sub(&mut self) -> Result<()> {
        
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in sub operation".to_string()));
        }
        
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
        
        match (a, b) {
            (Value::Integer(a), Value::Integer(b)) => {
                let _ = self.push_stack(Value::Integer(a - b));
                Ok(())
            },
            (Value::Float(a), Value::Float(b)) => {
                let _ = self.push_stack(Value::Float(a - b));
                Ok(())
            },
            (Value::Integer(a), Value::Float(b)) => {
                let _ = self.push_stack(Value::Float(a as f64 - b));
                Ok(())
            },
            (Value::Float(a), Value::Integer(b)) => {
                let _ = self.push_stack(Value::Float(a - b as f64));
                Ok(())
            },
            _ => Err(PipitError::TypeError("Cannot subtract non-numeric values".to_string())),
        }
    }
    
    /// 执行乘法指令
    pub fn execute_mul(&mut self) -> Result<()> {
        
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in mul operation".to_string()));
        }
        
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
        
        match (a, b) {
            (Value::Integer(a), Value::Integer(b)) => {
                let _ = self.push_stack(Value::Integer(a * b));
                Ok(())
            },
            (Value::Float(a), Value::Float(b)) => {
                let _ = self.push_stack(Value::Float(a * b));
                Ok(())
            },
            (Value::Integer(a), Value::Float(b)) => {
                let _ = self.push_stack(Value::Float(a as f64 * b));
                Ok(())
            },
            (Value::Float(a), Value::Integer(b)) => {
                let _ = self.push_stack(Value::Float(a * b as f64));
                Ok(())
            },
            _ => Err(PipitError::TypeError("Cannot multiply non-numeric values".to_string())),
        }
    }
    
    /// 执行除法指令
    pub fn execute_div(&mut self) -> Result<()> {
            
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in div operation".to_string()));
        }
        
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
        
        match (a, b) {
            (Value::Integer(a), Value::Integer(b)) => {
                if b == 0 {
                    Err(PipitError::DivisionByZeroError("Division by zero".to_string()))
                } else {
                    let _ = self.push_stack(Value::Integer(a / b));
                    Ok(())
                }
            },
            (Value::Float(a), Value::Float(b)) => {
                if b == 0.0 {
                    Err(PipitError::DivisionByZeroError("Division by zero".to_string()))
                } else {
                    let _ = self.push_stack(Value::Float(a / b));
                    Ok(())
                }
            },
            (Value::Integer(a), Value::Float(b)) => {
                if b == 0.0 {
                    Err(PipitError::DivisionByZeroError("Division by zero".to_string()))
                } else {
                    let _ = self.push_stack(Value::Float(a as f64 / b));
                    Ok(())
                }
            },
            (Value::Float(a), Value::Integer(b)) => {
                if b == 0 {
                    Err(PipitError::DivisionByZeroError("Division by zero".to_string()))
                } else {
                    let _ = self.push_stack(Value::Float(a / b as f64));
                    Ok(())
                }
            },
            _ => Err(PipitError::TypeError("Cannot divide non-numeric values".to_string())),
        }
    }

    /// 执行取模指令
    pub fn execute_mod(&mut self) -> Result<()> {

        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in mod operation".to_string()));
        }
         
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
         
        match (a, b) {
            (Value::Integer(a), Value::Integer(b)) => {
                if b == 0 {
                    Err(PipitError::DivisionByZeroError("Division by zero in mod operation".to_string()))
                } else {
                    let _ = self.push_stack(Value::Integer(a % b));
                    Ok(())
                }
            },
            (Value::Float(a), Value::Float(b)) => {
                if b == 0.0 {
                    Err(PipitError::DivisionByZeroError("Division by zero in mod operation".to_string()))
                } else {
                    let _ = self.push_stack(Value::Float(a % b));
                    Ok(())
                }
            },
            (Value::Integer(a), Value::Float(b)) => {
                if b == 0.0 {
                    Err(PipitError::DivisionByZeroError("Division by zero in mod operation".to_string()))
                } else {
                    let _ = self.push_stack(Value::Float(a as f64 % b));
                    Ok(())
                }
            },
            (Value::Float(a), Value::Integer(b)) => {
                if b == 0 {
                    Err(PipitError::DivisionByZeroError("Division by zero in mod operation".to_string()))
                } else {
                    let _ = self.push_stack(Value::Float(a % b as f64));
                    Ok(())
                }
            },
            _ => Err(PipitError::TypeError("Cannot perform mod operation on non-numeric values".to_string())),
        }
    }

    /// 执行求幂指令
    pub fn execute_pow(&mut self) -> Result<()> {
        // 检查是否有可用的预测结果（仅在启用JIT时）
         
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in pow operation".to_string()));
        }
         
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
         
        match (a, b) {
            (Value::Integer(a), Value::Integer(b)) => {
                // 处理特殊情况
                if a == 0 && b == 0 {
                    return Err(PipitError::RuntimeError("0^0 is undefined".to_string()));
                }
                
                // 检查是否可能溢出
                let exp = match b.try_into() {
                    Ok(exp_val) => exp_val,
                    Err(_) => return Err(PipitError::RuntimeError("Exponent too large".to_string()))
                };
                let result = a.pow(exp);
                
                let _ = self.push_stack(Value::Integer(result));
                Ok(())
            },
            (Value::Float(a), Value::Float(b)) => {
                // 处理特殊情况
                if a == 0.0 && b == 0.0 {
                    return Err(PipitError::RuntimeError("0.0^0.0 is undefined".to_string()));
                }
                
                let _ = self.push_stack(Value::Float(a.powf(b)));
                Ok(())
            },
            (Value::Integer(a), Value::Float(b)) => {
                // 处理特殊情况
                if a == 0 && b == 0.0 {
                    return Err(PipitError::RuntimeError("0^0.0 is undefined".to_string()));
                }
                
                let _ = self.push_stack(Value::Float((a as f64).powf(b)));
                Ok(())
            },
            (Value::Float(a), Value::Integer(b)) => {
                // 处理特殊情况
                if a == 0.0 && b == 0 {
                    return Err(PipitError::RuntimeError("0.0^0 is undefined".to_string()));
                }
                
                // 整数指数的特殊处理，提高效率
                if b >= 0 {
                    let _ = self.push_stack(Value::Float(a.powi(b)));
                } else {
                    let _ = self.push_stack(Value::Float(a.powi(b)));
                }
                Ok(())
            },
            _ => Err(PipitError::TypeError("Cannot perform pow operation on non-numeric values".to_string())),
        }
    }

    /// 执行相等比较指令
    pub fn execute_equal(&mut self) -> Result<()> {

        
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in equal operation".to_string()));
        }
        
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
        
        let result = match (a, b) {
            (Value::Null, Value::Null) => true,
            (Value::Null, _) | (_, Value::Null) => false,
            (Value::Integer(a), Value::Integer(b)) => a == b,
            (Value::Float(a), Value::Float(b)) => (a - b).abs() < 1e-9, // 浮点数比较使用近似相等
            (Value::Boolean(a), Value::Boolean(b)) => a == b,
            (Value::String(a), Value::String(b)) => a == b,
            (Value::Integer(a), Value::Float(b)) => (a as f64 - b).abs() < 1e-9,
            (Value::Float(a), Value::Integer(b)) => (a - b as f64).abs() < 1e-9,
            // 其他类型暂时不支持相等比较
            _ => false,
        };
        
        let _ = self.push_stack(Value::Boolean(result));
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 执行大于比较指令
    pub fn execute_greater_than(&mut self) -> Result<()> {
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in greater than operation".to_string()));
        }
        
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
        
        let result = match (a, b) {
            (Value::Null, _) | (_, Value::Null) => false,
            (Value::Integer(a), Value::Integer(b)) => a > b,
            (Value::Float(a), Value::Float(b)) => a > b,
            (Value::Integer(a), Value::Float(b)) => (a as f64) > b,
            (Value::Float(a), Value::Integer(b)) => a > (b as f64),
            // 其他类型暂时不支持大于比较
            _ => false,
        };
        
        let _ = self.push_stack(Value::Boolean(result));
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 执行小于比较指令
    pub fn execute_less_than(&mut self) -> Result<()> {
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in less than operation".to_string()));
        }
        
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
        
        let result = match (a, b) {
            (Value::Null, _) | (_, Value::Null) => false,
            (Value::Integer(a), Value::Integer(b)) => a < b,
            (Value::Float(a), Value::Float(b)) => a < b,
            (Value::Integer(a), Value::Float(b)) => (a as f64) < b,
            (Value::Float(a), Value::Integer(b)) => a < (b as f64),
            // 其他类型暂时不支持小于比较
            _ => false,
        };
        
        let _ = self.push_stack(Value::Boolean(result));
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 执行大于等于比较指令
    pub fn execute_greater_than_or_equal(&mut self) -> Result<()> {
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in greater than or equal operation".to_string()));
        }
        
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
        
        let result = match (a, b) {
            (Value::Null, _) | (_, Value::Null) => false,
            (Value::Integer(a), Value::Integer(b)) => a >= b,
            (Value::Float(a), Value::Float(b)) => a >= b,
            (Value::Integer(a), Value::Float(b)) => (a as f64) >= b,
            (Value::Float(a), Value::Integer(b)) => a >= (b as f64),
            // 其他类型暂时不支持大于等于比较
            _ => false,
        };
        
        let _ = self.push_stack(Value::Boolean(result));
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 执行小于等于比较指令
    pub fn execute_less_than_or_equal(&mut self) -> Result<()> {
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in less than or equal operation".to_string()));
        }
        
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
        
        let result = match (a, b) {
            (Value::Null, _) | (_, Value::Null) => false,
            (Value::Integer(a), Value::Integer(b)) => a <= b,
            (Value::Float(a), Value::Float(b)) => a <= b,
            (Value::Integer(a), Value::Float(b)) => (a as f64) <= b,
            (Value::Float(a), Value::Integer(b)) => a <= (b as f64),
            // 其他类型暂时不支持小于等于比较
            _ => false,
        };
        
        let _ = self.push_stack(Value::Boolean(result));
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 执行打印指令（不换行）
    pub fn execute_print(&mut self) -> Result<()> {
        if let Some(value) = self.pop_stack() {
            self.print_value_no_newline(&value)?;
            Ok(())
        } else {
            Err(PipitError::RuntimeError("Stack underflow in print operation".to_string()))
        }
    }
    
    /// 执行逻辑与操作指令
    pub fn execute_logical_and(&mut self) -> Result<()> {
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in logical and operation".to_string()));
        }
        
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
        
        let result = match (a, b) {
            (Value::Boolean(a), Value::Boolean(b)) => a && b,
            // 其他类型转换为布尔值后进行逻辑与操作
            (a, b) => self.to_boolean(&a) && self.to_boolean(&b),
        };
        
        let _ = self.push_stack(Value::Boolean(result));
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 执行逻辑或操作指令
    pub fn execute_logical_or(&mut self) -> Result<()> {
        // 常规执行逻辑
        if self.stack_len() < 2 {
            return Err(PipitError::RuntimeError("Stack underflow in logical or operation".to_string()));
        }
        
        let b = self.pop_stack().unwrap();
        let a = self.pop_stack().unwrap();
        
        let result = match (a, b) {
            (Value::Boolean(a), Value::Boolean(b)) => a || b,
            // 其他类型转换为布尔值后进行逻辑或操作
            (a, b) => self.to_boolean(&a) || self.to_boolean(&b),
        };
        
        let _ = self.push_stack(Value::Boolean(result));
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 执行逻辑非操作指令
    pub fn execute_not(&mut self) -> Result<()> {
        // 常规执行逻辑
        if self.stack_len() < 1 {
            return Err(PipitError::RuntimeError("Stack underflow in logical not operation".to_string()));
        }
        
        let value = self.pop_stack().unwrap();
        
        let result = match value {
            Value::Boolean(b) => !b,
            // 其他类型转换为布尔值后进行逻辑非操作
            other => !self.to_boolean(&other),
        };
        
        let _ = self.push_stack(Value::Boolean(result));
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 将值转换为布尔值
    fn to_boolean(&self, value: &Value) -> bool {
        match value {
            Value::Null => false,
            Value::Boolean(b) => *b,
            Value::Integer(i) => *i != 0,
            Value::Float(f) => *f != 0.0,
            Value::String(s) => !s.is_empty(),
            Value::Array(arr) => !arr.is_empty(),
            Value::Struct(s) => !s.is_empty(),
            Value::Instance(_) => true,  // 实例对象总是真值
            Value::Class(_) => true,     // 类定义总是真值
            Value::Function(_) => true,  // 函数总是真值
            Value::NativeFunction(_) => true, // 原生函数总是真值
            Value::CachedValue(v) => self.to_boolean(v),
            Value::Shared(_) => true,
        }
    }

    /// 执行打印指令（换行）
    pub fn execute_println(&mut self) -> Result<()> {
        if let Some(value) = self.pop_stack() {
            self.print_value(&value)?;
            Ok(())
        } else {
            Err(PipitError::RuntimeError("Stack underflow in println operation".to_string()))
        }
    }
    
    // 检查字符串是否为模块名
    fn is_module_name(&self, name: &str) -> bool {
        matches!(name, "core" | "io" | "math" | "string" | "os" | "concurrent" | "syscall")
    }
    
    // 将字符串转换为模块枚举
    fn string_to_module(&self, name: &str) -> Result<Module> {
        match name {
            "core" => Ok(Module::Core),
            "io" => Ok(Module::IO),
            "math" => Ok(Module::Math),
            "string" => Ok(Module::String),
            "os" => Ok(Module::OS),
            "concurrent" => Ok(Module::Concurrent),
            "syscall" => Ok(Module::Syscall),
            _ => Err(PipitError::ModuleError(format!("Unknown module: {}", name))),
        }
    }
    
    // 检查模块是否已加载
    pub fn is_module_loaded(&self, module: &Module) -> bool {
        self.module_registry.is_module_loaded(module)
    }
    
    /// 将值从栈虚拟机传输到RV32I虚拟机
    pub fn transfer_stack_to_riscv(&mut self, stack_index: usize, reg_index: u8) -> Result<()> {
        if stack_index < self.stack.len() {
            let value = self.stack[stack_index].clone();
            let riscv_vm = self.ensure_riscv_vm();
            riscv_vm.write_register(reg_index, value);
            Ok(())
        } else {
            Err(crate::error::PipitError::RuntimeError("Stack index out of bounds".to_string()))
        }
    }
    
    /// 将值从RV32I虚拟机传输到栈虚拟机
    pub fn transfer_riscv_to_stack(&mut self, reg_index: u8) -> Result<()> {
        // 确保 riscv vm 已初始化，然后读取寄存器
        let riscv_vm = self.ensure_riscv_vm();
        let value = riscv_vm.read_register(reg_index).clone();
        self.stack.push(value);
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 加载指令到RV32I虚拟机
    pub fn load_riscv_instructions(&mut self, instructions: Vec<RV32IInstruction>) -> Result<()> {
        let riscv_vm = self.ensure_riscv_vm();
        riscv_vm.load_instructions(instructions);
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 执行RV32I虚拟机中的流水线指令
    pub fn execute_riscv_pipeline(&mut self) -> Result<()> {
        let riscv_vm = self.ensure_riscv_vm();
        riscv_vm.execute_pipeline()
    }
    
    /// 重置RV32I虚拟机状态
    pub fn reset_riscv_vm(&mut self) -> Result<()> {
        let mut rv = RV32IVirtualMachine::new();
        rv.set_verbose(self.riscv_verbose);
        self.riscv_vm = Some(rv);
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 清除RV32I虚拟机中的所有指令
    pub fn clear_riscv_instructions(&mut self) -> Result<()> {
        let riscv_vm = self.ensure_riscv_vm();
        riscv_vm.instructions.clear();
        riscv_vm.pc = 0;
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    /// 执行预测性计算
    /// 这个方法被影子线程用来提前计算可能需要的表达式结果
    pub fn execute_prediction(&mut self, expression: &str, _params: Vec<u8>) -> Result<Vec<u8>> {
        // 在实际实现中，这里应该解析表达式并执行计算
        // 这里提供一个简单的示例实现，支持基本的算术表达式
        
        println!("Executing prediction for expression: {}", expression);
        
        // 解析简单的算术表达式，如"5+1", "10*2"等
        // 在实际实现中，应该使用更复杂的表达式解析器
        if expression.contains('+') {
            let parts: Vec<&str> = expression.split('+').collect();
            if parts.len() == 2 {
                if let (Ok(a), Ok(b)) = (parts[0].trim().parse::<i32>(), parts[1].trim().parse::<i32>()) {
                    let result = a + b;
                    // 序列化结果为整数
                    let mut serialized = Vec::new();
                    serialized.extend_from_slice(&result.to_le_bytes());
                    return Ok(serialized);
                }
            }
        } else if expression.contains('-') {
            let parts: Vec<&str> = expression.split('-').collect();
            if parts.len() == 2 {
                if let (Ok(a), Ok(b)) = (parts[0].trim().parse::<i32>(), parts[1].trim().parse::<i32>()) {
                    let result = a - b;
                    let mut serialized = Vec::new();
                    serialized.extend_from_slice(&result.to_le_bytes());
                    return Ok(serialized);
                }
            }
        } else if expression.contains('*') {
            let parts: Vec<&str> = expression.split('*').collect();
            if parts.len() == 2 {
                if let (Ok(a), Ok(b)) = (parts[0].trim().parse::<i32>(), parts[1].trim().parse::<i32>()) {
                    let result = a * b;
                    let mut serialized = Vec::new();
                    serialized.extend_from_slice(&result.to_le_bytes());
                    return Ok(serialized);
                }
            }
        } else if expression.contains('/') {
            let parts: Vec<&str> = expression.split('/').collect();
            if parts.len() == 2 {
                if let (Ok(a), Ok(b)) = (parts[0].trim().parse::<i32>(), parts[1].trim().parse::<i32>()) {
                    if b != 0 {
                        let result = a / b;
                        let mut serialized = Vec::new();
                        serialized.extend_from_slice(&result.to_le_bytes());
                        return Ok(serialized);
                    }
                }
            }
        }
        
        // 如果无法解析表达式，则返回错误
        Err(PipitError::RuntimeError(
            format!("Failed to execute prediction for expression: {}", expression)
        ))
    }
    
    /// 优化的对象分配方法 - 使用惰性数据内存池优化常用值的内存使用
    /// 对于常用的Integer, Boolean, Float和String类型的值，会尝试从惰性数据内存池中获取
    /// 其他类型的值直接使用ObjectStore的allocate_object方法
    fn allocate_optimized_object(&mut self, value: Value) -> Result<usize> {
        match &value {
            Value::Integer(i) => {
                // 存储到惰性数据内存池
                self.memory_pool.store_integer(*i)?;
                // 从惰性数据内存池获取（如果存在）
                let optimized_value = self.memory_pool.get_integer(*i)?;
                let obj_index = self.object_store.allocate_object(optimized_value);
                // 注册到GC
                self.concurrent_gc.register_allocated_object(obj_index);
                Ok(obj_index)
            },
            Value::Boolean(b) => {
                // 存储到惰性数据内存池
                self.memory_pool.store_boolean(*b)?;
                // 从惰性数据内存池获取（如果存在）
                let optimized_value = self.memory_pool.get_boolean(*b)?;
                let obj_index = self.object_store.allocate_object(optimized_value);
                // 注册到GC
                self.concurrent_gc.register_allocated_object(obj_index);
                Ok(obj_index)
            },
            Value::Float(f) => {
                // 存储到惰性数据内存池
                self.memory_pool.store_float(*f)?;
                // 从惰性数据内存池获取（如果存在）
                let optimized_value = self.memory_pool.get_float(*f)?;
                let obj_index = self.object_store.allocate_object(optimized_value);
                // 注册到GC
                self.concurrent_gc.register_allocated_object(obj_index);
                Ok(obj_index)
            },
            Value::String(s) => {
                // 根据字符串大小决定使用大对象池还是普通内存池
                let size = s.len();
                if size > 1024 { // 大字符串使用大对象池
                    let category = ObjectSize::classify(size);
                    let _pool_size = match category {
                        ObjectSize::Small(_) => 64 * 1024,
                        ObjectSize::Medium(_) => 256 * 1024,
                        ObjectSize::Large(_) => 1024 * 1024,
                        ObjectSize::Huge(_) => 4 * 1024 * 1024,
                    };
                    
                    // 使用大对象池分配
                    let result = self.large_object_pool.allocate(size, None);
                    if result.is_ok() {
                        // 创建包装值来管理大对象
                        let large_value = Value::String(s.clone());
                        let obj_index = self.object_store.allocate_object(large_value);
                        // 注册到GC
                        self.concurrent_gc.register_allocated_object(obj_index);
                        return Ok(obj_index);
                    }
                }
                
                // 小字符串使用惰性数据内存池
                self.memory_pool.store_string(s.clone())?;
                let optimized_value = self.memory_pool.get_string(s)?;
                let obj_index = self.object_store.allocate_object(optimized_value);
                // 注册到GC
                self.concurrent_gc.register_allocated_object(obj_index);
                Ok(obj_index)
            },
            Value::Array(arr) => {
                // 根据数组大小决定使用大对象池还是普通内存池
                let size = arr.len() * std::mem::size_of::<Value>();
                if size > 1024 { // 大数组使用大对象池
                    let category = ObjectSize::classify(size);
                    let _pool_size = match category {
                        ObjectSize::Small(_) => 64 * 1024,
                        ObjectSize::Medium(_) => 256 * 1024,
                        ObjectSize::Large(_) => 1024 * 1024,
                        ObjectSize::Huge(_) => 4 * 1024 * 1024,
                    };
                    
                    // 使用大对象池分配
                    let result = self.large_object_pool.allocate(size, None);
                    if result.is_ok() {
                        let obj_index = self.object_store.allocate_object(value);
                        // 注册到GC
                        self.concurrent_gc.register_allocated_object(obj_index);
                        return Ok(obj_index);
                    }
                }
                
                // 小数组使用普通分配
                let obj_index = self.object_store.allocate_object(value);
                // 注册到GC
                self.concurrent_gc.register_allocated_object(obj_index);
                Ok(obj_index)
            },
            // 其他类型的值使用普通分配
            _ => {
                let obj_index = self.object_store.allocate_object(value);
                // 注册到GC
                self.concurrent_gc.register_allocated_object(obj_index);
                Ok(obj_index)
            }
        }
    }

    /// 获取对象存储中的对象
    pub fn get_object(&self, index: usize) -> Result<&Value> {
        self.object_store.get_object_value(index)
    }

// 共享数据类型已在上方定义

// 删除重复的Value枚举定义

// 内联缓存状态
// 句柄收集器已在上方定义

// 虚拟机间通信数据包
// #[derive(Debug, Clone)]
// pub struct InterVMData {
//     pub data: SharedData,
//     pub source_vm: VMType,
//     pub target_vm: VMType,
// }

// #[derive(Debug, Clone, PartialEq)]
// pub enum VMType {
//     StackVM,
//     RegisterVM,
// }

// 虚拟机间通信接口
// pub trait InterVMCommunicator {
//     fn send_to_vm(&mut self, data: SharedData, target_vm: VMType) -> Result<()>;
//     fn receive_from_vm(&mut self, source_vm: VMType) -> Result<Option<SharedData>>;
//     fn transfer_data(&mut self, source_vm: VMType, target_vm: VMType) -> Result<()>;
// }

}

// 扩展虚拟机实现，添加通信功能
impl VirtualMachine {
    // 将栈顶元素转换为共享数据 - 暂时禁用
    pub fn stack_to_shared(&mut self) -> Result<SharedData> {
        if let Some(value) = self.stack.pop() {
            match value {
                Value::Shared(shared) => Ok(shared.clone_ref()),
                other => Ok(SharedData::new(other)),
            }
        } else {
            Err(PipitError::RuntimeError("Stack is empty".to_string()))
        }
    }
    
    // 将共享数据压入栈 - 暂时禁用
    pub fn shared_to_stack(&mut self, shared: SharedData) -> Result<()> {
        self.stack.push(Value::Shared(shared));
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    // 从寄存器读取共享数据 - 暂时禁用
    pub fn register_to_shared(&self, reg_index: u8) -> Result<SharedData> {
        if (reg_index as usize) < self.object_store.register_map.len() {
            if let Some(obj_index) = self.object_store.register_map[reg_index as usize] {
                let objects = &self.object_store.objects;
                if let Some(obj) = objects.get(obj_index) {
                    let value = &obj.value;
                    match value {
                        Value::Shared(shared) => Ok(shared.clone_ref()),
                        other => {
                            // 创建新的共享数据
                            let shared = SharedData::new(other.clone());
                            Ok(shared)
                        }
                    }
                } else {
                    Err(PipitError::RuntimeError("Object not found".to_string()))
                }
            } else {
                Err(PipitError::RuntimeError("Register is empty".to_string()))
            }
        } else {
            Err(PipitError::RuntimeError("Register index out of bounds".to_string()))
        }
    }
    
    // 将共享数据写入寄存器 - 暂时禁用
    pub fn shared_to_register(&mut self, shared: SharedData, reg_index: u8) -> Result<()> {
        let obj_index = self.object_store.allocate_object(Value::Shared(shared));
        // 直接将对象索引设置到指定寄存器（避免重复分配不同寄存器）
        self.object_store.set_register_value(reg_index, obj_index)?;
        // 从空闲寄存器列表中移除指定寄存器（如果仍存在）并更新计数
        if let Some(pos) = self.object_store.free_registers.iter().position(|&r| r == reg_index) {
            self.object_store.free_registers.remove(pos);
            if self.object_store.free_register_count > 0 {
                self.object_store.free_register_count -= 1;
            }
        }
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
    
    // 直接栈到寄存器的数据传输
    pub fn stack_to_register(&mut self, stack_index: usize, reg_index: u8) -> Result<()> {
        if stack_index < self.stack.len() {
            let value = self.stack.remove(stack_index);
            let obj_index = self.object_store.allocate_object(value);
            self.object_store.assign_register(obj_index)?;
            self.object_store.set_register_value(reg_index, obj_index)?;
            Ok(())
        } else {
            Err(PipitError::RuntimeError("Stack index out of bounds".to_string()))
        }
    }
    
    // 直接寄存器到栈的数据传输
    pub fn register_to_stack(&mut self, reg_index: u8) -> Result<()> {
        if (reg_index as usize) < self.object_store.register_map.len() {
            if let Some(&obj_index) = self.object_store.register_map[reg_index as usize].as_ref() {
                let value = self.object_store.get_object_value(obj_index)?;
                self.stack.push(value.clone());
                Ok(())
            } else {
                Err(PipitError::RuntimeError("Register is empty".to_string()))
            }
        } else {
            Err(PipitError::RuntimeError("Register index out of bounds".to_string()))
        }
    }

    // 获取大对象池的统计信息
    pub fn get_large_object_stats(&self) -> String {
        format!("Large Object Pool Stats: {:?}", self.large_object_pool.get_stats())
    }

    // 清理大对象池
    pub fn cleanup_large_objects(&mut self) {
        self.large_object_pool.cleanup();
    }

    // 根据对象大小智能选择分配策略
    pub fn smart_allocate(&mut self, value: Value) -> Result<usize> {
        let estimated_size = match &value {
            Value::String(s) => s.len(),
            Value::Array(arr) => arr.len() * std::mem::size_of::<Value>(),
            Value::Struct(map) => map.len() * (std::mem::size_of::<String>() + std::mem::size_of::<Value>()),
            _ => std::mem::size_of::<Value>(),
        };

        // 根据大小阈值选择分配策略
        if estimated_size > 1024 {
            // 大对象使用大对象池
            self.allocate_optimized_object(value)
        } else {
            // 小对象使用普通分配
            let obj_index = self.object_store.allocate_object(value);
            // 注册到GC
            self.concurrent_gc.register_allocated_object(obj_index);
            Ok(obj_index)
        }
    }

    pub fn register_module(&mut self, module: Module, loaded: bool) {
        self.module_registry.loaded_modules.insert(module, loaded);
    }

    pub fn load_module(&mut self, module: Module) -> Result<()> {
        self.module_registry.loaded_modules.insert(module, true);
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }

    pub fn unload_module(&mut self, module: Module) -> Result<()> {
        self.module_registry.loaded_modules.insert(module, false);
        // 强制刷新标准输出，确保在PowerShell中也能立即显示输出
    io::stdout().flush()?;
    Ok(())
    }
}
 // 修复：为 impl VirtualMachine 块添加缺失的闭合大括号
